Skip to content

Instantly share code, notes, and snippets.

@Korbeil
Last active June 7, 2022 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Korbeil/9e00073c29a26f55160abddcc9888757 to your computer and use it in GitHub Desktop.
Save Korbeil/9e00073c29a26f55160abddcc9888757 to your computer and use it in GitHub Desktop.
<?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