<?php
namespace App\Controller\Api;
use App\Utils\TranslationUtils;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
class EnumController extends AbstractController
{
/**
* @Route("/enum/{class}", name="enums", methods={"GET"})
*/
public function __invoke(
TranslatorInterface $translator,
AdapterInterface $cache,
TranslationUtils $translation,
string $class
): JsonResponse {
try {
$translatedData = $this->getCachedTranslatedEnum($class, $cache);
if (null === $translatedData) {
$translatedData = $this->translateEnumValues($class, $translator, $translation, $cache);
$this->cacheTranslatedEnum($class, $translatedData, $cache);
}
$response = $this->json($translatedData);
// Cache HTTP: Expire après une journée
$response->setPublic();
$response->setMaxAge(86400);
return $response;
} catch (\Exception $e) {
return $this->json([]);
}
}
private function getCachedTranslatedEnum(string $class, AdapterInterface $cache): ?array
{
$item = $cache->getItem($class);
return $item->isHit() ? $item->get() : null;
}
private function translateEnumValues(string $class, TranslatorInterface $translator, TranslationUtils $translation, AdapterInterface $cache): array
{
$cacheKey = $class.'_translated';
$cachedTranslations = $cache->getItem($cacheKey);
if (!$cachedTranslations->isHit()) {
$translatedData = [];
foreach (call_user_func('App\Enum\\'.$class.'::getChoices') as $key => $value) {
$translatedData[$value] = $translator->trans(
$translation->getReadableValue($key, $class)
);
}
$cachedTranslations->set($translatedData);
$cache->save($cachedTranslations);
}
return $cachedTranslations->get();
}
private function cacheTranslatedEnum(string $class, array $translatedData, AdapterInterface $cache): void
{
$item = $cache->getItem($class);
$item->set($translatedData);
$cache->save($item);
}
}