src/EventListener/LocaleListener.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. /**
  6.  * Class LocaleListener.
  7.  *
  8.  * The LocaleListener listens on the `kernel.request` event to correct the locale of the request if the site is not
  9.  * available in the requested locale.
  10.  *
  11.  * Priority is set to `300` to make sure the locale is set before it is used by, for example, translation services.
  12.  */
  13. class LocaleListener
  14. {
  15.     private ParameterBagInterface $parameterBag;
  16.     public function __construct(ParameterBagInterface $parameterBag)
  17.     {
  18.         $this->parameterBag $parameterBag;
  19.     }
  20.     /**
  21.      * Sets the locale of a request to the default locale if conditions are met.
  22.      *
  23.      * Sets the locale of a request to the value of the `site_translation_default_locale` parameter if
  24.      * 1. the site only has one language available or
  25.      * 2. the site is not available in the requested locale.
  26.      */
  27.     public function onKernelRequest(RequestEvent $event)
  28.     {
  29.         $request $event->getRequest();
  30.         $siteTranslationLocales $this->parameterBag->get('site_translation_locales');
  31.         if (\count($siteTranslationLocales) > && \in_array($request->getLocale(), $siteTranslationLocalestrue)) {
  32.             return;
  33.         }
  34.         $request->setLocale($this->parameterBag->get('site_translation_default_locale'));
  35.     }
  36. }