Created
November 24, 2015 16:45
-
-
Save Koalabaerchen/8ed60894cdbbdcd42f3c to your computer and use it in GitHub Desktop.
Locale Sessions in Symfony
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 | |
class LocaleListener implements EventSubscriberInterface | |
{ | |
private $defaultLocale; | |
public function __construct($defaultLocale = User::DEFAULT_LOCALE) | |
{ | |
$this->defaultLocale = $defaultLocale; | |
} | |
public function onKernelRequest(GetResponseEvent $event) | |
{ | |
$request = $event->getRequest(); | |
if (!$request->hasPreviousSession()) { | |
return; | |
} | |
if (false === $request->getSession()->isStarted()) { | |
$request->getSession()->start(); | |
} | |
// 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)); | |
} | |
} | |
/** | |
* Returns an array of event names this subscriber wants to listen to. | |
* | |
* The array keys are event names and the value can be: | |
* | |
* * The method name to call (priority defaults to 0) | |
* * An array composed of the method name to call and the priority | |
* * An array of arrays composed of the method names to call and respective | |
* priorities, or 0 if unset | |
* | |
* For instance: | |
* | |
* * array('eventName' => 'methodName') | |
* * array('eventName' => array('methodName', $priority)) | |
* * array('eventName' => array(array('methodName1', $priority), array('methodName2')) | |
* | |
* @return array The event names to listen to | |
* | |
* @api | |
*/ | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
// must be registered before the default Locale listener | |
KernelEvents::REQUEST => array( | |
array( | |
'onKernelRequest', | |
17, | |
), | |
), | |
); | |
} | |
} |
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
services: | |
User.localeListener: | |
class: User\UserBundle\EventListener\LocaleListener | |
arguments: ["%kernel.default_locale%"] | |
tags: | |
- { name: kernel.event_subscriber } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment