Created
May 4, 2016 01:10
-
-
Save miguelplazasr/d649074091b28674438bf6d1458ce4a3 to your computer and use it in GitHub Desktop.
Listener for set locale session
This file contains 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 AppBundle\EventListener; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\HttpKernel\KernelEvents; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
class LocaleListener implements EventSubscriberInterface | |
{ | |
private $defaultLocale; | |
public function __construct($defaultLocale = 'en') | |
{ | |
$this->defaultLocale = $defaultLocale; | |
} | |
public function onKernelRequest(GetResponseEvent $event) | |
{ | |
$request = $event->getRequest(); | |
if (!$request->hasPreviousSession()) { | |
return; | |
} | |
if ($locale = $request->attributes->get('_locale')) { | |
$request->getSession()->set('_locale', $locale); | |
} else { | |
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); | |
} | |
} | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
KernelEvents::REQUEST => array(array('onKernelRequest', 17)), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment