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

  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. public function __construct(private readonly TokenStorageInterface $tokenStorage, private readonly EntityManagerInterface $em)
  12. {
  13. }
  14. public function onKernelRequest(RequestEvent $event): void
  15. {
  16. if (null === $this->tokenStorage->getToken()) {
  17. return;
  18. }
  19. $user = $this->tokenStorage->getToken()->getUser();
  20. $locale = $event->getRequest()->attributes->get('_locale', 'ar');
  21. if ($user instanceof User && $user->getLanguage() !== $locale) {
  22. $user->setLanguage($locale);
  23. try {
  24. $this->em->persist($user);
  25. $this->em->flush($user);
  26. } catch (\Exception) {
  27. return;
  28. }
  29. }
  30. }
  31. public static function getSubscribedEvents(): array
  32. {
  33. return [
  34. KernelEvents::REQUEST => 'onKernelRequest',
  35. ];
  36. }
  37. }