Created
September 25, 2015 13:33
-
-
Save piwi91/64d0df409682693da3ea to your computer and use it in GitHub Desktop.
Symfony2 set locale from user profile setting
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\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\HttpKernel\Event\GetResponseEvent; | |
use Symfony\Component\HttpKernel\KernelEvents; | |
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; | |
} | |
// 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)); | |
} | |
} | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
// must be registered before the default Locale listener | |
KernelEvents::REQUEST => array(array('onKernelRequest', 17)), | |
); | |
} | |
} |
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\HttpFoundation\Session\Session; | |
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; | |
class UserLocaleListener | |
{ | |
/** | |
* @var Session | |
*/ | |
private $session; | |
public function __construct(Session $session) | |
{ | |
$this->session = $session; | |
} | |
/** | |
* @param InteractiveLoginEvent $event | |
*/ | |
public function onInteractiveLogin(InteractiveLoginEvent $event) | |
{ | |
$user = $event->getAuthenticationToken()->getUser(); | |
if (null !== $user->getLocale()) { | |
$this->session->set('_locale', $user->getLocale()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment