Skip to content

Commit

Permalink
🐛 Fix language redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
jbelien committed Sep 11, 2023
1 parent e6e68d5 commit 8fa9e7c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
1 change: 1 addition & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ services:
App\EventSubscriber\LocaleSubscriber:
arguments:
$defaultLocale: "%kernel.default_locale%"
$locales: "%app.locales%"
App\Service\RegionsProvider:
arguments:
$projectDirectory: "%kernel.project_dir%"
Expand Down
20 changes: 16 additions & 4 deletions src/EventSubscriber/LocaleSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@

class LocaleSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly string $defaultLocale)
{
/**
* @param string[] $locales
*
* @return void
*/
public function __construct(
private readonly string $defaultLocale,
private readonly array $locales
) {
}

public function onKernelRequest(RequestEvent $event)
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();

Expand All @@ -36,7 +43,12 @@ public function onKernelRequest(RequestEvent $event)
} elseif (\count($request->getLanguages()) > 0) {
// if we still don't have a locale defined, use the browser languages
$languages = $request->getLanguages();
$request->setLocale($languages[0]);
foreach ($languages as $lang) {
if (\in_array($lang, $this->locales, true)) {
$request->setLocale($lang);
break;
}
}
} else {
// or use the default locale
$request->setLocale($this->defaultLocale);
Expand Down

0 comments on commit 8fa9e7c

Please sign in to comment.