src/EventSubscriber/LocaleSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class LocaleSubscriber implements EventSubscriberInterface
  9. {
  10.     private $entityManager;
  11.     private $requestStack;
  12.     public function __construct(EntityManagerInterface $entityManagerRequestStack $requestStack)
  13.     {
  14.         $this->entityManager $entityManager;
  15.         $this->requestStack $requestStack;
  16.     }
  17.     public function onKernelRequest(RequestEvent $event)
  18.     {
  19.         if (!$event->isMainRequest()) {
  20.             return;
  21.         }
  22.         $request $this->requestStack->getCurrentRequest();
  23.         if (!$request->hasPreviousSession()) {
  24.             return;
  25.         }
  26.         $repository $this->entityManager->getRepository('App\Entity\User');
  27.         $session $request->getSession();
  28.         $user $repository->findOneByEmail($session->get('_security.last_username'));
  29.         if (!$user) {
  30.             // try to see if the locale has been set as a _locale routing parameter
  31.             if ($locale $request->attributes->get('_locale')) {
  32.                 $request->getSession()->set('_locale'$locale);
  33.             } else {
  34.                 // if no explicit locale has been set on this request, use one from the session
  35.                 $request->setLocale($request->getSession()->get('_locale''en'));
  36.             }
  37.         } else {
  38.             $language $user->getLanguage();
  39.             $request->setDefaultLocale($language);
  40.             $request->getSession()->set('_locale'$language);
  41.         }
  42.     }
  43.     public static function getSubscribedEvents()
  44.     {
  45.         return [
  46.             KernelEvents::REQUEST => [['onKernelRequest'15]],
  47.         ];
  48.     }
  49. }