-
-
Save Korbeil/9e00073c29a26f55160abddcc9888757 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Api\Statistics\Helper; | |
use Doctrine\ORM\EntityManagerInterface; | |
use Doctrine\ORM\QueryBuilder; | |
use App\Api\Rating\Rating; | |
use App\Api\Rating\Repository\RatingRepository; | |
use Psr\Cache\CacheItemPoolInterface; | |
class RatingsDistribution | |
{ | |
private const EMPTY_DISTRIBUTION = [ | |
1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, | |
6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0, | |
]; | |
private const CACHE_KEY = 'ratings_distribution_%s'; | |
private const CACHE_TTL = 60 * 10; // 10 min cache TTL | |
private ?QueryBuilder $baseBuilder = null; | |
public function __construct( | |
private RatingRepository $ratingRepository, | |
private CacheItemPoolInterface $cacheApp, | |
) { | |
} | |
public function getCached(string $bookId): array | |
{ | |
$cacheItem = $this->cacheApp->getItem(sprintf(self::CACHE_KEY, $bookId)); | |
if (!$cacheItem->isHit()) { | |
$cacheItem->set($this->get($bookId)); | |
$cacheItem->expiresAfter(self::CACHE_TTL); | |
$this->cacheApp->save($cacheItem); | |
} | |
return $cacheItem->get(); | |
} | |
private function get(string $bookId): array | |
{ | |
$distribution = $this->makeQueryForBook($bookId); | |
if (null === $distribution) { | |
return self::EMPTY_DISTRIBUTION; | |
} | |
$localDistribution = self::EMPTY_DISTRIBUTION; | |
foreach ($distribution as $result) { | |
$localDistribution[$result['rating']] = $result['count']; | |
} | |
return $localDistribution; | |
} | |
private function makeQueryForBook(string $bookId): ?array | |
{ | |
if (null === $this->baseBuilder) { | |
$this->baseBuilder = $this | |
->ratingRepository | |
->createQueryBuilder('r') | |
->select('r.rating, COUNT(r.id) as count') | |
->andWhere('r.book = :bookId') | |
->groupBy('r.rating'); | |
} | |
return (clone $this->baseBuilder) | |
->setParameter('bookId', $bookId) | |
->getQuery() | |
->getResult(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment