<?php
namespace App\Subscriber;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\LocaleAwareInterface;
class UserLocaleSubscriber implements EventSubscriberInterface
{
/** @var Security */
private $security;
/** @var iterable<LocaleAwareInterface> */
private iterable $localeAwareServices;
public function __construct(Security $security, iterable $localeAwareServices)
{
$this->security = $security;
$this->localeAwareServices = $localeAwareServices;
}
public function onControllerEvent(ControllerEvent $event)
{
$user = $this->security->getUser();
if (!$user instanceof User) {
return;
}
$lang = $user->getLanguage();
foreach ($this->localeAwareServices as $localeAwareService) {
$localeAwareService->setLocale($lang);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onControllerEvent',
];
}
}