src/EventListener/LocaleListener.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\User\User;
  4. use App\Service\NotificationService\NotificationService;
  5. use Symfony\Component\ErrorHandler\Exception\FlattenException;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\Session\Session;
  9. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  10. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  11. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  12. use Symfony\Component\HttpKernel\Event\RequestEvent;
  13. use Symfony\Component\Routing\RouterInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
  15. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  16. use Symfony\Component\Security\Core\Security;
  17. use Symfony\Component\Translation\Translator;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. class LocaleListener
  20. {
  21.     public function __construct(
  22.         private readonly RequestStack $requestStack,
  23.         private readonly TokenStorageInterface $tokenStorage,
  24.         private readonly TranslatorInterface $translator
  25.     )
  26.     {
  27.     }
  28.     public function onKernelRequest(RequestEvent $event)
  29.     {
  30.         $user $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null;
  31.         $locale $this->requestStack->getCurrentRequest()->getSession()->get('locale') ?: @$_COOKIE['locale'] ?: null;
  32.         if($locale) {
  33.             $this->translator->setLocale(strtolower($locale));
  34.         }elseif($user){
  35.             $this->translator->setLocale(strtolower($user->getLocale()));
  36.         }
  37.     }
  38. }