src/Subscriber/UserLocaleSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\Subscriber;
  3. use App\Entity\User;
  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\LocaleAwareInterface;
  9. class UserLocaleSubscriber implements EventSubscriberInterface
  10. {
  11.     /** @var Security */
  12.     private $security;
  13.     /** @var iterable<LocaleAwareInterface> */
  14.     private iterable $localeAwareServices;
  15.     public function __construct(Security $securityiterable $localeAwareServices)
  16.     {
  17.         $this->security $security;
  18.         $this->localeAwareServices $localeAwareServices;
  19.     }
  20.     public function onControllerEvent(ControllerEvent $event)
  21.     {
  22.         $user $this->security->getUser();
  23.         if (!$user instanceof User) {
  24.             return;
  25.         }
  26.         $lang $user->getLanguage();
  27.         foreach ($this->localeAwareServices as $localeAwareService) {
  28.             $localeAwareService->setLocale($lang);
  29.         }
  30.     }
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             KernelEvents::CONTROLLER => 'onControllerEvent',
  35.         ];
  36.     }
  37. }