<?php
namespace App\EventListener;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
/**
* Class LocaleListener.
*
* The LocaleListener listens on the `kernel.request` event to correct the locale of the request if the site is not
* available in the requested locale.
*
* Priority is set to `300` to make sure the locale is set before it is used by, for example, translation services.
*/
class LocaleListener
{
private ParameterBagInterface $parameterBag;
public function __construct(ParameterBagInterface $parameterBag)
{
$this->parameterBag = $parameterBag;
}
/**
* Sets the locale of a request to the default locale if conditions are met.
*
* Sets the locale of a request to the value of the `site_translation_default_locale` parameter if
* 1. the site only has one language available or
* 2. the site is not available in the requested locale.
*/
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$siteTranslationLocales = $this->parameterBag->get('site_translation_locales');
if (\count($siteTranslationLocales) > 1 && \in_array($request->getLocale(), $siteTranslationLocales, true)) {
return;
}
$request->setLocale($this->parameterBag->get('site_translation_default_locale'));
}
}