File: D:/HostingSpaces/SBogers10/farmfun.komma.pro/app/Komma/Kiyoh/KiyohService.php
<?php
namespace App\Komma\Kiyoh;
use App\Komma\Base\Service;
use App\Komma\Kiyoh\Models\Review;
use Illuminate\Database\Eloquent\Collection;
final class KiyohService extends Service
{
private static $reviewsByLocations;
public function __construct()
{
parent::__construct();
if (! self::$reviewsByLocations) {
self::$reviewsByLocations = Review::select('rating', 'location_id')->get()->groupBy('location_id');
}
}
/**
* @param int $locationId
* @return object
*/
public function getScoreForLocation(int $locationId)
{
$reviewsForLocation = self::$reviewsByLocations->get($locationId);
if (! isset($reviewsForLocation)) {
return null;
}
$averageNumber = round($reviewsForLocation->avg('rating'), 1) ?? 9.4;
$totalReviews = $reviewsForLocation->count() ?? 100;
$stars = $this->kiyohReviewStarsObject($averageNumber);
return (object) ['averageNumber' => $averageNumber, 'totalReviews' => $totalReviews, 'stars' => $stars];
}
/**
* @return object
*/
public function getTotalScore()
{
$averageNumber = round(self::$reviewsByLocations->flatten()->avg('rating'), 1) ?? 9.4;
$totalReviews = self::$reviewsByLocations->flatten()->count() ?? 1409;
$stars = $this->kiyohReviewStarsObject($averageNumber);
return (object) ['averageNumber' => $averageNumber, 'totalReviews' => $totalReviews, 'stars' => $stars];
}
/**
* @param int $rating
* @param int $limit
* @return Collection
*/
public function getLastReviews(int $rating = 8, int $limit = 48): Collection
{
return Review::where('rating', '>=', $rating)
->orderBy('created_at', 'desc')
->take($limit)
->get();
}
public function kiyohReviewStarsObject($rating)
{
$fullStars = intval(floor($rating / 2));
$halfStar = ($rating - (2 * $fullStars)) > 0 ? 1 : 0;
$emptyStars = 5 - $fullStars - $halfStar;
return (object) ['full' => $fullStars, 'half' => $halfStar, 'empty' => $emptyStars];
}
}