<?php
namespace Moka\Cms\Admin\EventSubscriber;
use Moka\Cms\Entity\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
class UserLocaleSubscriber implements EventSubscriberInterface
{
public function __construct(private RequestStack $requestStack)
{
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof UserInterface and $user->getLocale()) {
$this->requestStack->getSession()->set('_locale', $user->getLocale());
}
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
if ($locale = $this->requestStack->getSession()->get('_locale')) {
$request->setLocale($locale);
}
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}