<?php
namespace AppBundle\EventSubscriber;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleSubscriber implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct(ContainerInterface $container)
{
// detect default user locale from browser preferences
//TODO: this is a hotfix. We are waiting for foreign language content. Disabling other languages for now.
// $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$lang = "cs";
$acceptLang = $container->getParameter('locales');
$defaultLocale = in_array($lang, $acceptLang) ? $lang : $container->getParameter('locale');
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// 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));
}
// TODO: maybe need to define currency here as well ?
}
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}