src\EventListener\LocaleSubscriber.php line 38

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