src/EventSubscriber/LocaleSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Contracts\Translation\TranslatorInterface;
  8. use Twig\Environment;
  9. class LocaleSubscriber implements EventSubscriberInterface
  10. {
  11.     private $translator;
  12.     private $session;
  13.     private $environment;
  14.     
  15.     public function __construct(TranslatorInterface $translatorSessionInterface $sessionEnvironment $environment)
  16.     {
  17.         $this->translator $translator;
  18.         $this->session $session;
  19.         $this->environment $environment;
  20.     }
  21.     public function onKernelController(ControllerEvent $event)
  22.     {
  23.         $request =  $event->getRequest();
  24.         $locale $request->getSession()->get('localeSession');
  25.         $locale $locale ?? 'fr';
  26.         $this->translator->setLocale($locale);
  27.         $this->environment->addGlobal('app_default_locale'$locale);   
  28.         $GLOBALS['app_default_locale'] = $locale;
  29.     }
  30.     public static function getSubscribedEvents()
  31.     {
  32.         return [
  33.             KernelEvents::CONTROLLER => 'onKernelController',
  34.         ];
  35.     }
  36. }