src/EventSubscriber/SetLanguageSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. class SetLanguageSubscriber implements EventSubscriberInterface
  11. {
  12.     private $tokenStorage;
  13.     private $translator;
  14.     public function __construct(TranslatorInterface $translatorTokenStorageInterface $tokenStorage)
  15.     {
  16.         $this->translator $translator;
  17.         $this->tokenStorage $tokenStorage;
  18.     }
  19.     public static function getSubscribedEvents()
  20.     {
  21.         return array(
  22.             KernelEvents::CONTROLLER => 'setLanguage',
  23.         );
  24.     }
  25.     public function setLanguage(ControllerEvent $event)
  26.     {
  27.         if (strpos($event->getRequest()->getPathInfo(), 'dashboard') !== false) {
  28.             $token $this->tokenStorage->getToken();
  29.             if (!$token) {
  30.                 return;
  31.             }
  32.             /** @var User $user */
  33.             $user $token->getUser();
  34.             if (is_string($user)) {
  35.                 return;
  36.             }
  37.             $locale $user->getLocale();
  38.             $event->getRequest()->setLocale($locale);
  39.             $this->translator->setLocale($locale);
  40.         }
  41.     }
  42. }