src/EventSubscriber/LocaleSubscriber.php line 41

Open in your IDE?
  1. <?php
  2.     namespace App\EventSubscriber;
  3.     use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4.     use Symfony\Component\HttpKernel\Event\RequestEvent;
  5.     use Symfony\Component\HttpKernel\KernelEvents;
  6.     use Twig\Environment;
  7.     class LocaleSubscriber implements EventSubscriberInterface
  8.     {
  9.         private $defaultLocale;
  10.         private $twig;
  11.         public function __construct(string $defaultLocale "en"Environment $twig)
  12.         {
  13.             $this->twig $twig;
  14.             $this->defaultLocale $defaultLocale;
  15.         }
  16.         public function onKernelRequest(RequestEvent $event)
  17.         {
  18.             $request $event->getRequest();
  19.             if (!$request->hasPreviousSession()) {
  20.                 // return;
  21.             }
  22.             if ($locale $request->query->get('_locale')) {
  23.                 $globals $this->twig->getGlobals();
  24.                 if (in_array($locale$globals['locales'])) {
  25.                     $this->defaultLocale $locale;
  26.                 }
  27.                 $request->getSession()->set('_locale'$this->defaultLocale);
  28.                 $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  29.             } else {
  30.                 // if no explicit locale has been set on this request, use one from the session
  31.                 $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  32.             }
  33.         }
  34.         public static function getSubscribedEvents()
  35.         {
  36.             return [
  37.                 // must be registered before (i.e. with a higher priority than) the default Locale listener
  38.                 KernelEvents::REQUEST => [['onKernelRequest'0]],
  39.             ];
  40.         }
  41.     }