src/EventListener/LocaleListener.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Sylius\Bundle\ShopBundle\Locale\LocaleSwitcherInterface;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  7. use Symfony\Component\Routing\RequestContextAwareInterface;
  8. class LocaleListener
  9. {
  10.     /** @var LocaleSwitcherInterface */
  11.     private $localeSwitcher;
  12.     private $container;
  13.     private $request;
  14.     private $router;
  15.     const LOCALES = array(
  16.         'ro',
  17.         'en',
  18.         'tr',
  19.         'hu',
  20.         'bg',
  21.         'de',
  22.         'it',
  23.         'ru'
  24.     );
  25.     public function __construct(
  26.         LocaleSwitcherInterface $localeSwitcher,
  27.         RequestStack $requestStack,
  28.         ContainerInterface $container,
  29.         RequestContextAwareInterface $router
  30.     ) {
  31.         $this->request $requestStack->getCurrentRequest();
  32.         $this->localeSwitcher $localeSwitcher;
  33.         $this->container $container;
  34.         $this->router $router;
  35.     }
  36.     public function onKernelRequest(GetResponseEvent $event)
  37.     {
  38.         $session $this->request->getSession();
  39.         $localeCode 'ro';
  40.         if ($session->has('localeCode')) {
  41.             $localeCode $session->get('localeCode');
  42.         }
  43.         if ($this->request->get('_locale')) {
  44.             $localeCode $this->request->get('_locale');
  45.             $session->set('localeCode'$localeCode);
  46.         }
  47.         $localeCode LocaleListener::checkIfGiveLocaleIsValid($localeCode) ? $localeCode 'ro';
  48.         $this->container->get('translator')->setLocale($localeCode);
  49.         $this->request->getSession()->set('_locale'$localeCode);
  50.         $this->request->setLocale($localeCode);
  51.         $this->request->setDefaultLocale($localeCode);
  52.         $this->localeSwitcher->handle($this->request$localeCode);
  53.         $this->router->getContext()->setParameter('_locale'$localeCode);
  54.     }
  55.     public static function checkIfGiveLocaleIsValid($locale)
  56.     {
  57.         $isValid false;
  58.         if (ctype_alpha($locale) && in_array($localeLocaleListener::LOCALES)) {
  59.             $isValid true;
  60.         }
  61.         return $isValid;
  62.     }
  63. }