src/EventSubscriber/LocaleSubscriber.php line 20

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. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8.     private $defaultLocale;
  9.     public function __construct($defaultLocale 'fr')
  10.     {
  11.         $this->defaultLocale $defaultLocale;
  12.     }
  13.     public function onKernelRequest(RequestEvent $event){
  14.         $request $event->getRequest();
  15.         if(!$request->hasPreviousSession()){
  16.             return;
  17.         }
  18.         if($locale $request->query->get('_locale')){
  19.             $request->setLocale($locale);
  20.         }else{
  21.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  22.         }
  23.     }
  24.     /**
  25.      * Returns an array of event names this subscriber wants to listen to.
  26.      *
  27.      * The array keys are event names and the value can be:
  28.      *
  29.      *  * The method name to call (priority defaults to 0)
  30.      *  * An array composed of the method name to call and the priority
  31.      *  * An array of arrays composed of the method names to call and respective
  32.      *    priorities, or 0 if unset
  33.      *
  34.      * For instance:
  35.      *
  36.      *  * ['eventName' => 'methodName']
  37.      *  * ['eventName' => ['methodName', $priority]]
  38.      *  * ['eventName' => [['methodName1', $priority], ['methodName2']]]
  39.      *
  40.      * @return array The event names to listen to
  41.      */
  42.     public static function getSubscribedEvents()
  43.     {
  44.         return [
  45.           KernelEvents::REQUEST => [['onKernelRequest'20]],
  46.         ];
  47.     }
  48. }