<?php
declare(strict_types=1);
namespace Slivki\Repository\ServerFeature;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Slivki\Entity\ServerFeatureState;
use Slivki\Exception\ServerFeatureStateNotFoundException;
use function array_key_exists;
use function count;
final class ServerFeatureStateRepository extends ServiceEntityRepository implements ServerFeatureStateRepositoryInterface
{
/**
* @var array<int, ServerFeatureState>
*/
private array $runtimeCache = [];
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ServerFeatureState::class);
}
public function getById(int $featureStateId): ServerFeatureState
{
if (array_key_exists($featureStateId, $this->runtimeCache)) {
return $this->runtimeCache[$featureStateId];
}
$queryBuilder = $this->createQueryBuilder('sfs');
$expr = $queryBuilder->expr();
$serverFeatureState = $queryBuilder
->andWhere($expr->eq('sfs.id', ':id'))
->setParameter(':id', $featureStateId)
->getQuery()
->getOneOrNullResult();
if (!$serverFeatureState instanceof ServerFeatureState) {
throw new ServerFeatureStateNotFoundException();
}
$this->runtimeCache[$featureStateId] = $serverFeatureState;
return $this->runtimeCache[$featureStateId];
}
public function findAll(): array
{
if (count($this->runtimeCache) > 0) {
return $this->runtimeCache;
}
$queryBuilder = $this->createQueryBuilder('sfs');
/** @var array<ServerFeatureState> $serverFeatures */
$serverFeatures = $queryBuilder
->getQuery()
->getResult();
foreach ($serverFeatures as $serverFeature) {
$this->runtimeCache[$serverFeature->getId()] = $serverFeature;
}
return $this->runtimeCache;
}
}