<?php
namespace App\Form\Type;
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use App\Model\IriNormalizableInterface;
use App\Service\ApiWebServiceFilterBuilder\PaginationFilterBuilder;
use App\Service\Cache\CacheManager;
use App\V4\Logger\SentryLogger;
use Psr\Cache\CacheException;
use Psr\Cache\InvalidArgumentException;
use Throwable;
trait SubresourceChoicesTrait
{
/**
* @throws CacheException
* @throws InvalidArgumentException
*/
private function getChoices(
CollectionDataProviderInterface $collectionDataProvider,
CacheManager $cacheManager,
SentryLogger $sentryLogger,
string $entityFQCN,
array $filters,
string $getterLabel,
string $getterValue
): array {
$entityChoices = $this->getEntityChoices($collectionDataProvider, $cacheManager, $sentryLogger, $entityFQCN, $filters);
$choices = [];
foreach ($entityChoices as $entity) {
$choices[$entity->$getterLabel()] = $entity->$getterValue();
}
return $choices;
}
/**
* @throws CacheException
* @throws InvalidArgumentException
* @throws \Exception
*/
private function getEntityChoices(
CollectionDataProviderInterface $collectionDataProvider,
CacheManager $cacheManager,
SentryLogger $sentryLogger,
string $entityFQCN,
array $filters = []
): iterable {
$key = $entityFQCN;
$choices = $cacheManager->get($key, __METHOD__.'_'.serialize($filters));
if (null !== $choices) {
unset($choices['isCache'], $choices['cacheDate']);
return $choices;
}
try {
$choices = $collectionDataProvider->getCollection($entityFQCN, null, [
'filters' => array_merge($filters, [PaginationFilterBuilder::ACTIVATE_PAGNIATION_KEY => false]),
]);
foreach ($choices as $entity) {
if ($entity instanceof IriNormalizableInterface) {
$entity->setNormalizeAsIRI(true);
}
}
$cacheManager->set($key, __METHOD__.'_'.serialize($filters), $choices);
return $choices;
} catch (Throwable $exception) {
$sentryLogger->captureException(
SentryLogger::CHANNEL_DATA_RETRIEVER,
$exception,
[
'catchOnClass' => get_class($this),
'entitySearched' => $entityFQCN,
'filters' => serialize($filters),
]
);
}
return [];
}
}