src/EventListener/LocaleListener.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. /**
  7.  * This event is triggered after a particular KernalRequest so its processed during page preload
  8.  * Used for switching locale - found in symfony cookbook.
  9.  */
  10. class LocaleListener implements EventSubscriberInterface
  11. {
  12.     public function __construct(private $defaultLocale 'en')
  13.     {
  14.     }
  15.     public function onKernelRequest(RequestEvent $event)
  16.     {
  17.         $request $event->getRequest();
  18.         if (!$request->hasPreviousSession()) {
  19.             return;
  20.         }
  21.         // try to see if the locale has been set as a _locale routing parameter
  22.         if ($request->attributes->get('_locale')) {
  23.             $locale $request->attributes->get('_locale');
  24.             $request->getSession()->set('_locale'$locale);
  25.             $request->setLocale($locale);
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  29.         }
  30.         $route $request->get('_route''');
  31.         if (str_contains((string) $route'control_')) {
  32.             $request->getSession()->set('_locale'$this->defaultLocale);
  33.             $request->setLocale($this->defaultLocale);
  34.         }
  35.     }
  36.     public static function getSubscribedEvents()
  37.     {
  38.         return [
  39.             // must be registered before the default Locale listener
  40.             KernelEvents::REQUEST => [['onKernelRequest'17]],
  41.         ];
  42.     }
  43. }