Lines
100.00%
8 / 8
Functions and Methods
100.00%
2 / 2
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| LocaleListener | 100.00% | 8 / 8 | 100.00% | 2 / 2 | 4 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| __invoke | 100.00% | 7 / 7 | 100.00% | 1 / 1 | 3 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace App\EventListener; | |
| 6 | ||
| 7 | use App\Controller\Locale\Switcher; | |
| 8 | use Symfony\Component\DependencyInjection\Attribute\Autowire; | |
| 9 | use Symfony\Component\EventDispatcher\Attribute\AsEventListener; | |
| 10 | use Symfony\Component\HttpKernel\Event\RequestEvent; | |
| 11 | use Symfony\Component\HttpKernel\KernelEvents; | |
| 12 | ||
| 13 | /** | |
| 14 | * The language of a request: the one chosen with the language switcher (a cookie), else the | |
| 15 | * browser's preferred one of the enabled locales. Before Symfony's LocaleListener (16), which | |
| 16 | * only overrides it with a `_locale` route attribute (there is none). | |
| 17 | */ | |
| 18 | #[AsEventListener(event: KernelEvents::REQUEST, priority: 20)] | |
| 19 | final readonly class LocaleListener | |
| 20 | { | |
| 21 | /** | |
| 22 | * @param list<string> $enabledLocales | |
| 23 | */ | |
| 24 | public function __construct( | |
| 25 | #[Autowire(param: 'kernel.enabled_locales')] | |
| 26 | private array $enabledLocales, | |
| 27 | ) { | |
| 28 | } | |
| 29 | ||
| 30 | public function __invoke(RequestEvent $event): void | |
| 31 | { | |
| 32 | if (!$event->isMainRequest()) { | |
| 33 | return; | |
| 34 | } | |
| 35 | ||
| 36 | $request = $event->getRequest(); | |
| 37 | $chosen = $request->cookies->getString(Switcher::COOKIE); | |
| 38 | $request->setLocale(\in_array($chosen, $this->enabledLocales, true) | |
| 39 | ? $chosen | |
| 40 | : $request->getPreferredLanguage($this->enabledLocales) ?? $request->getDefaultLocale()); | |
| 41 | } | |
| 42 | } |