Skip to content

Instantly share code, notes, and snippets.

@enricofoltran
Created April 3, 2013 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enricofoltran/5302455 to your computer and use it in GitHub Desktop.
Save enricofoltran/5302455 to your computer and use it in GitHub Desktop.
Symfony locale listener
<?php
namespace Acme\Bundle\I18nBundle\EventListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class LocaleListener
{
private $container;
private $locales;
public function __construct(ContainerInterface $container, array $locales)
{
$this->container = $container;
$this->locales = $locales;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
$locale = $request->getPreferredLanguage($this->locales);
if($this->container->has('session')) {
$session = $this->container->get('session');
if($session->get('_locale', false)) {
$request->setLocale($session->get('_locale'));
return;
}
$session->set('_locale', $locale);
}
$request->setLocale($locale);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment