src/EventListener/LocaleListener.php line 17

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.     public function onKernelRequest(RequestEvent $event)
  14.     {
  15.         $request $event->getRequest();
  16.         if (!$request->hasPreviousSession()) {
  17.             return;
  18.         }
  19.         // try to see if the locale has been set as a _locale routing parameter
  20.         if ($request->attributes->get('_locale')) {
  21.             $locale $request->attributes->get('_locale');
  22.             $request->getSession()->set('_locale'$locale);
  23.             $request->setLocale($locale);
  24.         } else {
  25.             // if no explicit locale has been set on this request, use one from the session
  26.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  27.         }
  28.         $route $request->get('_route''');
  29.         if (str_contains((string) $route'control_')) {
  30.             $request->getSession()->set('_locale'$this->defaultLocale);
  31.             $request->setLocale($this->defaultLocale);
  32.         }
  33.     }
  34.     public static function getSubscribedEvents()
  35.     {
  36.         return [
  37.             // must be registered before the default Locale listener
  38.             KernelEvents::REQUEST => [['onKernelRequest'17]],
  39.         ];
  40.     }
  41. }