src/Aqarmap/Bundle/UserBundle/EventListener/LocaleEventSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace Aqarmap\Bundle\UserBundle\EventListener;
  3. use Aqarmap\Bundle\UserBundle\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. class LocaleEventSubscriber implements EventSubscriberInterface
  10. {
  11.     private TokenStorageInterface $tokenStorage;
  12.     private EntityManagerInterface $em;
  13.     public function __construct(TokenStorageInterface $tokenStorageEntityManagerInterface $em)
  14.     {
  15.         $this->tokenStorage $tokenStorage;
  16.         $this->em $em;
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         if (null === $this->tokenStorage->getToken()) {
  21.             return;
  22.         }
  23.         $user $this->tokenStorage->getToken()->getUser();
  24.         $locale $event->getRequest()->attributes->get('_locale''ar');
  25.         if ($user instanceof User && $user->getLanguage() !== $locale) {
  26.             $user->setLanguage($locale);
  27.             try {
  28.                 $this->em->persist($user);
  29.                 $this->em->flush($user);
  30.             } catch (\Exception $exception) {
  31.                 return;
  32.             }
  33.         }
  34.     }
  35.     public static function getSubscribedEvents(): array
  36.     {
  37.         return [
  38.             KernelEvents::REQUEST => 'onKernelRequest',
  39.         ];
  40.     }
  41. }