Created
April 16, 2016 21:12
-
-
Save rigobertocontreras/2cd8bc4b2b722cc7a5894fc4f48da8d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\MainBundle\Listener; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\HttpKernel\KernelEvents; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\Security\Core\SecurityContext; | |
use Symfony\Component\HttpKernel\HttpKernel; | |
use Doctrine\ORM\EntityManager; | |
use Acme\UserBundle\Entity\User; | |
class LocaleListener implements EventSubscriberInterface | |
{ | |
private $defaultLocale; | |
private $securityContext; | |
private $em; | |
public function __construct($defaultLocale = 'fr', SecurityContext $securityContext, EntityManager $em) | |
{ | |
$this->defaultLocale = $defaultLocale; | |
$this->securityContext = $securityContext; | |
$this->em = $em; | |
} | |
public function onKernelRequest(GetResponseEvent $event) | |
{ | |
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) { | |
return; | |
} | |
$request = $event->getRequest(); | |
// Impersonate account check | |
if (!$request->hasPreviousSession()) { | |
return; | |
} | |
$user = null; | |
if ($this->securityContext->getToken()) { | |
$user = $this->securityContext->getToken()->getUser(); | |
} | |
if ($locale = $request->get('_locale')) { | |
$request->getSession()->set('_locale', $locale); | |
if (null !== $user && $user != 'anon.' && $user->getLocale() !== $locale) { | |
$user->setLocale($locale); | |
$this->em->persist($user); | |
$this->em->flush(); | |
} | |
} | |
else if ($user instanceof User && null !== $user->getLocale()) { | |
$request->getSession()->set('_locale', $user->getLocale()); | |
} | |
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); | |
} | |
static public function getSubscribedEvents() | |
{ | |
return array( | |
// must be registered before the default Locale listener | |
KernelEvents::REQUEST => array(array('onKernelRequest', -50)), | |
); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment