src/EventSubscriber/LocaleSubscriber.php line 25

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. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. class LocaleSubscriber implements EventSubscriberInterface
  11. {
  12.     private $defaultLocale;
  13.     public function __construct(string $defaultLocale 'en'Security $securityTokenStorageInterface $tsTranslatorInterface $trans)
  14.     {
  15.         $this->defaultLocale    $defaultLocale;
  16.         $this->trans            $trans;
  17.         $this->security         $security;
  18.         $this->tokenStorage     $ts;
  19.     }
  20.     public function onKernelRequest(ControllerEvent $event)
  21.     {
  22.         $request $event->getRequest();
  23.         if (!$event->isMainRequest()) {
  24.             return;
  25.         }
  26.         if (!$token $this->tokenStorage->getToken()) {
  27.             return ;
  28.         }
  29.         if (!$token->isAuthenticated()) {
  30.             return ;
  31.         }
  32.         if (!$user $token->getUser()) {
  33.             return ;
  34.         }
  35.         $request->setLocale(strtolower($token->getUser()->getUsuIdioma()));
  36.         $this->trans->setLocale(strtolower($token->getUser()->getUsuIdioma()));
  37.     }
  38.     public static function getSubscribedEvents()
  39.     {
  40.         return [
  41.             //KernelEvents::REQUEST => [['onKernelController', 20]],
  42.             //'kernel.request' => 'onKernelRequest',
  43.             KernelEvents::CONTROLLER => ['onKernelRequest', -120]
  44.         ];
  45.     }
  46. }