<?php
/**
* Created by Mediterranean Develup Solutions.
* User: Carlos.Rojas
* Date: 22/06/2017
* Time: 10:16
*/
namespace App\EventSubscriber;
use App\Entity\User;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class LocaleSubscriber implements EventSubscriberInterface
{
protected $em;
public function __construct(EntityManager $em){
$this->em = $em;
}
public function onKernelRequest(RequestEvent $event)
{
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
return;
}
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
$repository = $this->em->getRepository(User::class);
$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 {
$idioma = $user->getLanguage();
$request->setDefaultLocale($idioma);
$request->getSession()->set('_locale', $idioma);
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}