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($defaultLocale, EntityManagerInterface $manager, Environment $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.         // Dev nástroje (náhled e-mailů) nepotřebují DB, ať jdou spustit i bez ní.
  39.         if (str_starts_with((string) $request->attributes->get('_route'), 'dev_')) {
  40.             return;
  41.         }
  42.         $locales = [];
  43.         foreach ($this->em->getRepository(Language::class)->findAll() as $language) {
  44.             $locales[$language->getCode()] = $language->getDateFormat();
  45.         }
  46.         // try to see if the locale has been set as a _locale routing parameter
  47.         if ($locale = $request->attributes->get('_locale')) {
  48.             if (!in_array($locale, array_keys($locales))) {
  49.                 $event->setResponse(new Response($this->twig->render('404.html.twig'), 404));
  50.             }
  51.             $request->getSession()->set('_locale', $locale);
  52.         } else {
  53.             // if no explicit locale has been set on this request, use one from the session
  54.             $locale = $request->getSession()->get('_locale', $this->defaultLocale);
  55.             $request->setLocale($locale);
  56.         }
  57.         $request->attributes->set('date_format', $locales[$locale] ?? 'Y-m-d H:i:s');
  58.     }
  59.     /**
  60.      * {@inheritdoc}
  61.      */
  62.     public static function getSubscribedEvents()
  63.     {
  64.         return array(
  65.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  66.             KernelEvents::REQUEST => array(array('onKernelRequest', 20)),
  67.         );
  68.     }
  69. }