src/Event/EventSubscriber/LocaleSubscriber.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Event\EventSubscriber;
  3. use App\Api\BrcBackend\TranslationClient;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Contracts\Cache\CacheInterface;
  9. use Symfony\Contracts\Cache\ItemInterface;
  10. class LocaleSubscriber implements EventSubscriberInterface
  11. {
  12.     private CacheInterface $cache;
  13.     private TranslationClient $translationClient;
  14.     public function __construct(
  15.         CacheInterface $cache,
  16.         TranslationClient $translationClient 
  17.     ) {
  18.         $this->cache $cache;
  19.         $this->translationClient $translationClient;
  20.     }
  21.     public function onKernelRequest(RequestEvent $event): void
  22.     {
  23.         if (!$event->isMainRequest()) {
  24.             return;
  25.         }
  26.         $request $event->getRequest();
  27.         $locale $request->getLocale();
  28.         if (!$this->isLocaleEnabled($locale)) {
  29.             // $request->setLocale('pl');
  30.             // $request->attributes->set('_locale', 'pl');
  31.             throw new NotFoundHttpException('Locale not allowed.');
  32.         }
  33.     }
  34.     public function isLocaleEnabled(string $locale): bool
  35.     {
  36.         return $this->cache->get(
  37.             'is_locale_enabled_' $locale
  38.             function (ItemInterface $item) use ($locale) {
  39.             $item->expiresAfter(300); 
  40.          
  41.             $result $this->translationClient->isEnabledLocale($locale);
  42.             if (isset($result['localeEnabled']) && $result['localeEnabled'] == true) {
  43.                 return true;
  44.             }
  45.             return false;
  46.         });
  47.     }
  48.     public static function getSubscribedEvents(): array
  49.     {
  50.         return [
  51.             KernelEvents::REQUEST => ['onKernelRequest'20],
  52.         ];
  53.     }
  54. }