<?php
namespace App\EventSubscriber;
use App\Entity\AdminUser;
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\TranslatorInterface;
class LocaleSubscriber implements EventSubscriberInterface
{
private ?AdminUser $user;
private TranslatorInterface $translator;
public function __construct(Security $security, TranslatorInterface $translator)
{
$this->user = $security->getUser();
$this->translator = $translator;
}
public function setLocale(ControllerEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if ($this->user) {;
$request->setLocale($this->user->locale);
$this->translator->setLocale($this->user->locale);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => [['setLocale', 1]],
];
}
}