src/Controller/Api/EnumController.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Api;
  3. use App\Utils\TranslationUtils;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Cache\Adapter\AdapterInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Contracts\Translation\TranslatorInterface;
  9. class EnumController extends AbstractController
  10. {
  11.     /**
  12.      * @Route("/enum/{class}", name="enums", methods={"GET"})
  13.      */
  14.     public function __invoke(
  15.         TranslatorInterface $translator,
  16.         AdapterInterface $cache,
  17.         TranslationUtils $translation,
  18.         string $class
  19.     ): JsonResponse {
  20.         try {
  21.             $translatedData $this->getCachedTranslatedEnum($class$cache);
  22.             if (null === $translatedData) {
  23.                 $translatedData $this->translateEnumValues($class$translator$translation$cache);
  24.                 $this->cacheTranslatedEnum($class$translatedData$cache);
  25.             }
  26.             $response $this->json($translatedData);
  27.             // Cache HTTP: Expire après une journée
  28.             $response->setPublic();
  29.             $response->setMaxAge(86400);
  30.             return $response;
  31.         } catch (\Exception $e) {
  32.             return $this->json([]);
  33.         }
  34.     }
  35.     private function getCachedTranslatedEnum(string $classAdapterInterface $cache): ?array
  36.     {
  37.         $item $cache->getItem($class);
  38.         return $item->isHit() ? $item->get() : null;
  39.     }
  40.     private function translateEnumValues(string $classTranslatorInterface $translatorTranslationUtils $translationAdapterInterface $cache): array
  41.     {
  42.         $cacheKey $class.'_translated';
  43.         $cachedTranslations $cache->getItem($cacheKey);
  44.         if (!$cachedTranslations->isHit()) {
  45.             $translatedData = [];
  46.             foreach (call_user_func('App\Enum\\'.$class.'::getChoices') as $key => $value) {
  47.                 $translatedData[$value] = $translator->trans(
  48.                     $translation->getReadableValue($key$class)
  49.                 );
  50.             }
  51.             $cachedTranslations->set($translatedData);
  52.             $cache->save($cachedTranslations);
  53.         }
  54.         return $cachedTranslations->get();
  55.     }
  56.     private function cacheTranslatedEnum(string $class, array $translatedDataAdapterInterface $cache): void
  57.     {
  58.         $item $cache->getItem($class);
  59.         $item->set($translatedData);
  60.         $cache->save($item);
  61.     }
  62. }