Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add frontend language cookie functionality #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 68 additions & 22 deletions Classes/Middleware/LanguageRedirectMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ class LanguageRedirectMiddleware implements MiddlewareInterface
#[Flow\InjectConfiguration(path: 'languageCodeOverrides')]
protected array $languageCodeOverrides;

#[Flow\InjectConfiguration(path: 'feLanguageCookieName')]
protected string $feLanguageCookieName;

/**
* Redirect all requests to the homepage without a language prefix to the
* homepage with the language that matches the browser language best.
Expand Down Expand Up @@ -52,9 +55,18 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface

$defaultPreset = $this->contentDimensionPresetSource->getDefaultPreset('language');

$preset = $this->findMatchingPresetByAcceptLanguageHeader(
$request->getHeader('Accept-Language')[0] ?? '',
);
$preset = null;

if ($this->feLanguageCookieName && isset($request->getCookieParams()[$this->feLanguageCookieName])) {
$feLanguageCookie = $request->getCookieParams()[$this->feLanguageCookieName];
$preset = $this->findMatchingPresetByFeLanguageCookie($feLanguageCookie);
}

if ($preset == null) {
$preset = $this->findMatchingPresetByAcceptLanguageHeader(
$request->getHeader('Accept-Language')[0] ?? '',
);
}

if ($preset == null) {
$preset = $defaultPreset;
Expand All @@ -63,9 +75,9 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
if ($preset === null) {
throw new Exception(
'Unable to find a language preset for the detected locale '
. 'and no default preset is configured. '
. 'Check your content dimensions settings: '
. 'Neos.ContentRepository.contentDimensions.language.',
. 'and no default preset is configured. '
. 'Check your content dimensions settings: '
. 'Neos.ContentRepository.contentDimensions.language.',
1701173151780
);
}
Expand Down Expand Up @@ -93,31 +105,65 @@ protected function findMatchingPresetByAcceptLanguageHeader(string $acceptLangua
$acceptLanguageHeader
);

if (!$detectedLocale instanceof Locale) {
$resolvedLocale = $this->resolveLocale($detectedLocale);

if ($resolvedLocale === null) {
// No Locale found, continue with next part
array_shift($parts);
$acceptLanguageHeader = implode(',', $parts);
continue;
}

$languageCode = $detectedLocale->getLanguage();
if (isset($this->languageCodeOverrides[$languageCode])) {
// If there is a language code override, use it
$languageCode = $this->languageCodeOverrides[$languageCode];
}
return $resolvedLocale;
}

$preset = $this->contentDimensionPresetSource->findPresetByUriSegment(
'language',
$languageCode
);
return null;
}

if ($preset !== null) {
return $preset;
}
/**
* Match frontend language cookie against given language dimensions.
* Return the Locale, that fits best.
*
* @param string $acceptLanguageHeader
*
* @return array|null
*/
protected function findMatchingPresetByFeLanguageCookie(string $feLanguageCookie): ?array
{
$detectedLocale = $this->localeDetector->detectLocaleFromLocaleTag($feLanguageCookie);

return $this->resolveLocale($detectedLocale);
}

/**
* Resolve a locale string and return it
*
* @param string $acceptLanguageHeader
*
* @return array|null
*/
protected function resolveLocale(string $localeString): ?array
{
$detectedLocale = $this->localeDetector->detectLocaleFromLocaleTag($localeString);

if (!$detectedLocale instanceof Locale) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please move L150-168 to a new function and use it in both findMatchingPresetBy... methods?
Sth. like:

$detectedLocale = 'dependsOnMethod';

$preset = $this->findPresetByLocale($detectedLocale);

// For the presetByLanguageCookie one can directly return $preset.
// This check is only neccessary in the AcceptLanguageHeader while loop.
if ($preset !== null) {
    return $preset;
}

// ...

// No Locale found
return null;
}

$languageCode = $detectedLocale->getLanguage();
if (isset($this->languageCodeOverrides[$languageCode])) {
// If there is a language code override, use it
$languageCode = $this->languageCodeOverrides[$languageCode];
}

$preset = $this->contentDimensionPresetSource->findPresetByUriSegment(
'language',
$languageCode
);

// No preset for the detected locale found, continue with next part
array_shift($parts);
$acceptLanguageHeader = implode(',', $parts);
if ($preset !== null) {
return $preset;
}

return null;
Expand Down
2 changes: 2 additions & 0 deletions Configuration/Settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ Wegmeister:
LanguageRedirect:
# Add mappings for language codes if you use some different codes than the default ones.
languageCodeOverrides: {}
# Configure the name of your frontend language cookie name
feLanguageCookieName: ''
7 changes: 7 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ Then run `composer update` in your project root.
## Configuration

Sometimes language codes are not configured the same as in Neos. Therefore you can configure a mapping in your `Settings.yaml`:
Also you can configure a feLanguageCookieName to get a cookie value from your frontend in case you want your users last
opened language to reopen the next time he visits your website.
The `feLanguageCookieName` allows you to read a cookie that contains a default language.
Perhaps you can use this to always load the last language the user opened
by setting the cookie when he changes the language via the language menu on your website.

```yaml
Wegmeister:
Expand All @@ -23,4 +28,6 @@ Wegmeister:
languageCodeOverrides:
# For example, if you use "cz" instead of "cs" for Czech, you can add this mapping:
cs: cz
# configure the name of your frontend language cookie
feLanguageCookieName: _fe_language
```