<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* This event is triggered after a particular KernalRequest so its processed during page preload
* Used for switching locale - found in symfony cookbook.
*/
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($request->attributes->get('_locale')) {
$locale = $request->attributes->get('_locale');
$request->getSession()->set('_locale', $locale);
$request->setLocale($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));
}
$route = $request->get('_route');
if (false !== strpos($route, 'control_')) {
$request->getSession()->set('_locale', $this->defaultLocale);
$request->setLocale($this->defaultLocale);
}
}
public static function getSubscribedEvents()
{
return [
// must be registered before the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 17]],
];
}
}