public static parseAcceptLanguageHeader ( string $acceptLanguageHeader ) : mixed | ||
$acceptLanguageHeader | string | |
return | mixed | The array of locale identifiers or FALSE |
public static function parseAcceptLanguageHeader($acceptLanguageHeader)
{
$acceptLanguageHeader = str_replace(' ', '', $acceptLanguageHeader);
$matchingLanguages = [];
if (preg_match_all(self::PATTERN_MATCH_ACCEPTLANGUAGE, $acceptLanguageHeader, $matches, \PREG_PATTERN_ORDER) !== false) {
foreach ($matches[1] as $localeIdentifier) {
if ($localeIdentifier === '*') {
$matchingLanguages[] = $localeIdentifier;
continue;
}
if (strpos($localeIdentifier, '-') !== false) {
list($language, $region) = explode('-', $localeIdentifier);
} else {
$language = $localeIdentifier;
$region = null;
}
if (strlen($language) >= 2 && strlen($language) <= 3) {
if ($region === null || strlen($region) >= 2 && strlen($region) <= 3) {
// Note: there are 3 chars in the region code only if they are all digits, but we don't check it above
$matchingLanguages[] = $localeIdentifier;
}
}
}
if (count($matchingLanguages) > 0) {
return $matchingLanguages;
}
}
return false;
}
/** * Returns best-matching Locale object based on the Accept-Language header * provided as parameter. System default locale will be returned if no * successful matches were done. * * @param string $acceptLanguageHeader The Accept-Language HTTP header * @return Locale Best-matching existing Locale instance * @api */ public function detectLocaleFromHttpHeader($acceptLanguageHeader) { $acceptableLanguages = I18n\Utility::parseAcceptLanguageHeader($acceptLanguageHeader); if ($acceptableLanguages === false) { return $this->localizationService->getConfiguration()->getDefaultLocale(); } foreach ($acceptableLanguages as $languageIdentifier) { if ($languageIdentifier === '*') { return $this->localizationService->getConfiguration()->getDefaultLocale(); } try { $locale = new Locale($languageIdentifier); } catch (Exception\InvalidLocaleIdentifierException $exception) { continue; } $bestMatchingLocale = $this->localeCollection->findBestMatchingLocale($locale); if ($bestMatchingLocale !== null) { return $bestMatchingLocale; } } return $this->localizationService->getConfiguration()->getDefaultLocale(); }