src/EventSubscriber/LocaleSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Language;
  4. use App\Utils\LanguageUtil;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Twig\Environment;
  11. class LocaleSubscriber implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var string
  15.      */
  16.     private $defaultLocale;
  17.     /**
  18.      * @var EntityManagerInterface
  19.      */
  20.     private $em;
  21.     /**
  22.      * @var Environment
  23.      */
  24.     private $twig;
  25.     public function __construct($defaultLocaleEntityManagerInterface $managerEnvironment $twig)
  26.     {
  27.         $this->defaultLocale $defaultLocale;
  28.         $this->em $manager;
  29.         $this->twig $twig;
  30.     }
  31.     public function onKernelRequest(RequestEvent $event): void
  32.     {
  33.         //TODO: nekontrolujeme, zda-li locale je v DB
  34.         $request $event->getRequest();
  35.         if (!$request->hasPreviousSession()) {
  36.             return;
  37.         }
  38.         $locales = [];
  39.         foreach ($this->em->getRepository(Language::class)->findAll() as $language) {
  40.             $locales[$language->getCode()] = $language->getDateFormat();
  41.         }
  42.         // try to see if the locale has been set as a _locale routing parameter
  43.         if ($locale $request->attributes->get('_locale')) {
  44.             if (!in_array($localearray_keys($locales))) {
  45.                 $event->setResponse(new Response($this->twig->render('404.html.twig'), 404));
  46.             }
  47.             $request->getSession()->set('_locale'$locale);
  48.         } else {
  49.             // if no explicit locale has been set on this request, use one from the session
  50.             $locale $request->getSession()->get('_locale'$this->defaultLocale);
  51.             $request->setLocale($locale);
  52.         }
  53.         $request->attributes->set('date_format'$locales[$locale] ?? 'Y-m-d H:i:s');
  54.     }
  55.     /**
  56.      * {@inheritdoc}
  57.      */
  58.     public static function getSubscribedEvents()
  59.     {
  60.         return array(
  61.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  62.             KernelEvents::REQUEST => array(array('onKernelRequest'20)),
  63.         );
  64.     }
  65. }