<?php
namespace App\EventSubscriber;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class LocaleSubscriber implements EventSubscriberInterface
{
private $entityManager;
private $requestStack;
public function __construct(EntityManagerInterface $entityManager, RequestStack $requestStack)
{
$this->entityManager = $entityManager;
$this->requestStack = $requestStack;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$request = $this->requestStack->getCurrentRequest();
if (!$request->hasPreviousSession()) {
return;
}
$repository = $this->entityManager->getRepository('App\Entity\User');
$session = $request->getSession();
$user = $repository->findOneByEmail($session->get('_security.last_username'));
if (!$user) {
// 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', 'en'));
}
} else {
$language = $user->getLanguage();
$request->setDefaultLocale($language);
$request->getSession()->set('_locale', $language);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 15]],
];
}
}