<?php
namespace App\EventListener;
use Sylius\Bundle\ShopBundle\Locale\LocaleSwitcherInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\RequestContextAwareInterface;
class LocaleListener
{
/** @var LocaleSwitcherInterface */
private $localeSwitcher;
private $container;
private $request;
private $router;
const LOCALES = array(
'ro',
'en',
'tr',
'hu',
'bg',
'de',
'it',
'ru',
'tr',
'pl',
'uk',
'fr',
'nl',
'cs',
'sr',
'sk',
'es',
'el',
'hr',
'sv',
'no',
);
public function __construct(
LocaleSwitcherInterface $localeSwitcher,
RequestStack $requestStack,
ContainerInterface $container,
RequestContextAwareInterface $router
) {
$this->request = $requestStack->getCurrentRequest();
$this->localeSwitcher = $localeSwitcher;
$this->container = $container;
$this->router = $router;
}
public function onKernelRequest(GetResponseEvent $event)
{
$session = $this->request->getSession();
$localeCode = 'ro';
if ($session->has('localeCode')) {
$localeCode = $session->get('localeCode');
}
if ($this->request->get('_locale')) {
$localeCode = $this->request->get('_locale');
$session->set('localeCode', $localeCode);
}
$localeCode = LocaleListener::checkIfGiveLocaleIsValid($localeCode) ? $localeCode : 'ro';
$this->container->get('translator')->setLocale($localeCode);
$this->request->getSession()->set('_locale', $localeCode);
$this->request->setLocale($localeCode);
$this->request->setDefaultLocale($localeCode);
$this->localeSwitcher->handle($this->request, $localeCode);
$this->router->getContext()->setParameter('_locale', $localeCode);
}
public static function checkIfGiveLocaleIsValid($locale)
{
$isValid = false;
if (ctype_alpha($locale) && in_array($locale, LocaleListener::LOCALES)) {
$isValid = true;
}
return $isValid;
}
}