Better language detection from HTTP header
This commit is contained in:
parent
cd9433cc5c
commit
31fa1bb65a
|
@ -103,16 +103,32 @@ class LanguageUtils {
|
||||||
* @return Language|null user language if determined, null otherwise
|
* @return Language|null user language if determined, null otherwise
|
||||||
*/
|
*/
|
||||||
public function detectUserLanguage(): ?Language {
|
public function detectUserLanguage(): ?Language {
|
||||||
if (isset($_COOKIE["tswebsite_language"])) { // check cookie
|
// check cookie
|
||||||
$langcode = $_COOKIE["tswebsite_language"];
|
if (isset($_COOKIE["tswebsite_language"])) {
|
||||||
} else if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) { // check http headers
|
$lang = $this->getLanguageByCode($_COOKIE["tswebsite_language"]);
|
||||||
$langcode = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2);
|
|
||||||
|
if ($lang !== null) {
|
||||||
|
return $lang;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// if language with that code exists, return it
|
// check Accept-Language HTTP header
|
||||||
if(!empty($langcode) && ($lang = $this->getLanguageByCode($langcode))) {
|
if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
|
||||||
|
$langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
|
||||||
|
|
||||||
|
// find and return first language that our website supports
|
||||||
|
// TODO would be best to sort the list by their weights, but modern
|
||||||
|
// browsers seem to send the list that is already sorted
|
||||||
|
foreach ($langs as $lang) {
|
||||||
|
// IE adds an extra space - trim to remove it
|
||||||
|
$langcode = trim(explode(";", $lang)[0]);
|
||||||
|
$lang = $this->getLanguageByCode($langcode);
|
||||||
|
|
||||||
|
if ($lang !== null) {
|
||||||
return $lang;
|
return $lang;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue