src/EventSubscriber/LocaleSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\AdminUser;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Contracts\Translation\TranslatorInterface;
  9. class LocaleSubscriber implements EventSubscriberInterface
  10. {
  11.     private ?AdminUser $user;
  12.     private TranslatorInterface $translator;
  13.     public function __construct(Security $securityTranslatorInterface $translator)
  14.     {
  15.         $this->user $security->getUser();
  16.         $this->translator $translator;
  17.     }
  18.     public function setLocale(ControllerEvent $event): void
  19.     {
  20.         if (!$event->isMainRequest()) {
  21.             return;
  22.         }
  23.         $request $event->getRequest();
  24.         if ($this->user) {;
  25.             $request->setLocale($this->user->locale);
  26.             $this->translator->setLocale($this->user->locale);
  27.         }
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             KernelEvents::CONTROLLER => [['setLocale'1]],
  33.         ];
  34.     }
  35. }