<?php
namespace App\Subscriber;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* Stores the locale of the user in the session after the
* login. This can be used by the LocaleSubscriber afterwards.
*/
class LocaleSubscriber implements EventSubscriberInterface
{
/** @var SessionInterface $session */
protected $session;
/** @var string $defaultLocale */
protected $defaultLocale;
public function __construct(SessionInterface $session)
{
$this->session = $session;
$this->defaultLocale = User::LOCALE_FR;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// if on admin, locale is always en
$adminPath = '/admin';
if (substr($request->getPathInfo(), 0, strlen($adminPath)) == $adminPath) {
$request->setLocale(User::LOCALE_FR);
return;
}
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public function onInteractiveLogin(InteractiveLoginEvent $event)
{
/** @var User $user */
$user = $event->getAuthenticationToken()->getUser();
if (null !== $user->getUserData()->getInfoLocale()) {
$this->session->set('_locale', $user->getUserData()->getInfoLocale());
}
}
public static function getSubscribedEvents()
{
return [
SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}