Skip to content

Commit 0490107

Browse files
jonasraoniGaziYucel
authored andcommitted
Feature main 7512 use accept language (#10611)
* #7512 Added Accept-Language header into the locale detection * #7512 Fixed call to PKPRequest::getPreferredLanguage() * #7512 Give preference to the server preferred locale if there's no match with the Accept-Language header * #7512 Updated code to use the Laravel request directly
1 parent 2778d11 commit 0490107

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

classes/core/PKPRequest.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ class PKPRequest
6565
/** @var string user agent */
6666
public string $_userAgent;
6767

68-
6968
/**
7069
* get the router instance
7170
*/
@@ -593,7 +592,7 @@ public function getUserVar(string $key): mixed
593592
{
594593
// special treatment for APIRouter. APIHandler gets to fetch parameter first
595594
$router = $this->getRouter();
596-
595+
597596
if ($router instanceof \PKP\core\APIRouter && (!is_null($handler = $router->getHandler()))) {
598597
$handler = $router->getHandler(); /** @var \PKP\handler\APIHandler $handler */
599598
$value = $handler->getApiController()->getParameter($key);

classes/i18n/Locale.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,8 @@ public function getLocale(): string
134134
$request = $this->_getRequest();
135135
$locale = $request->getUserVar('setLocale')
136136
?: $request->getSession()->get('currentLocale')
137-
?: $request->getCookieVar('currentLocale');
137+
?: $request->getCookieVar('currentLocale')
138+
?: $this->getPreferredLocale();
138139
$this->setLocale($locale);
139140
return $this->locale;
140141
}
@@ -582,4 +583,19 @@ private function _getSubmissionLocaleNames(): array
582583
->toArray());
583584
})();
584585
}
586+
587+
/**
588+
* Retrieve the preferred user locale from our supported locales using the Accept-Language header
589+
* If there's no match, it falls back to the server's primary locale
590+
*/
591+
private function getPreferredLocale(): ?string
592+
{
593+
$serverPreference = $this->getPrimaryLocale() ?: LocaleInterface::DEFAULT_LOCALE;
594+
$supportedLocales = array_values($this->_getSupportedLocales());
595+
// Move the server preference to the top, in case the user preference doesn't match with the supported locales, the server one will be picked
596+
if (is_int($index = array_search($serverPreference, $supportedLocales))) {
597+
array_splice($supportedLocales, $index, 1);
598+
}
599+
return app(\Illuminate\Http\Request::class)->getPreferredLanguage([$serverPreference, ...$supportedLocales]);
600+
}
585601
}

0 commit comments

Comments
 (0)