src/EventListener/LocaleListener.php line 25

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: grego
  5.  * Date: 18/10/2022
  6.  * Time: 16:22
  7.  */
  8. namespace App\EventListener;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpKernel\Event\RequestEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. class LocaleListener implements EventSubscriberInterface
  13. {
  14.     private $defaultLocale;
  15.     public function __construct($defaultLocale 'en')
  16.     {
  17.         $this->defaultLocale $defaultLocale;
  18.     }
  19.     public function onKernelRequest(RequestEvent $event)
  20.     {
  21.         $request $event->getRequest();
  22.         if (!$request->hasPreviousSession()) {
  23.             return;
  24.         }
  25.         // try to see if the locale has been set as a _locale routing parameter
  26.         if ($locale $request->attributes->get('_locale')) {
  27.             $request->getSession()->set('_locale'$locale);
  28.         } else {
  29.             // if no explicit locale has been set on this request, use one from the session
  30.             if($request->getSession()->get('_locale')){
  31.                 $request->setLocale($request->getSession()->get('_locale'));
  32.             } else {
  33.                 $request->setLocale($this->defaultLocale);
  34.             }
  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. }