src/AppBundle/EventSubscriber/LocaleSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace AppBundle\EventSubscriber;
  3. use Symfony\Component\DependencyInjection\ContainerInterface;
  4. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. class LocaleSubscriber implements EventSubscriberInterface
  8. {
  9.     private $defaultLocale;
  10.     public function __construct(ContainerInterface $container)
  11.     {
  12.         // detect default user locale from browser preferences
  13.         //TODO: this is a hotfix. We are waiting for foreign language content. Disabling other languages for now.
  14. //        $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  15.         $lang "cs";
  16.         $acceptLang $container->getParameter('locales');
  17.         $defaultLocale in_array($lang$acceptLang) ? $lang $container->getParameter('locale');
  18.         $this->defaultLocale $defaultLocale;
  19.     }
  20.     public function onKernelRequest(GetResponseEvent $event)
  21.     {
  22.         $request $event->getRequest();
  23.         // try to see if the locale has been set as a _locale routing parameter
  24.         if ($locale $request->attributes->get('_locale')) {
  25.             $request->getSession()->set('_locale'$locale);
  26.         } else {
  27.             // if no explicit locale has been set on this request, use one from the session
  28.             $request->setLocale($request->getSession()->get('_locale'$this->defaultLocale));
  29.         }
  30.         // TODO: maybe need to define currency here as well ?
  31.     }
  32.     public static function getSubscribedEvents()
  33.     {
  34.         return [
  35.             // must be registered before (i.e. with a higher priority than) the default Locale listener
  36.             KernelEvents::REQUEST => [['onKernelRequest'20]],
  37.         ];
  38.     }
  39. }