Skip to content

Commit

Permalink
feat: add Common::getLanguageFromBrowser()
Browse files Browse the repository at this point in the history
  • Loading branch information
winternet-studio committed Jan 21, 2025
1 parent d8b570a commit 1f8bc98
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,32 @@ public static function restoreLanguage() {
}
}

/**
* Determine language from browser header
*
* Example header: `Accept-Language: de-DE,de;q=0.9,en;q=0.8`
*
* @param array $supportedLanguages : Supported languages, eg. `['en-US', 'da-DK', 'de-DE']`
* @return string|null : Eg. `da-DK` if the language is found
*/
public static function getLanguageFromBrowser($supportedLanguages) {
foreach (\Yii::$app->request->getAcceptableLanguages() as $acceptableLanguage) { //copied from yii\web\Request class. Example: `['en-GB', 'en']`. Yii puts them in their prioritized order.
$acceptableLanguage = str_replace('_', '-', strtolower($acceptableLanguage));
foreach ($supportedLanguages as $language) {
$normalizedLanguage = str_replace('_', '-', strtolower($language));

if (
$normalizedLanguage === $acceptableLanguage // en-us==en-us
|| strpos($acceptableLanguage, $normalizedLanguage . '-') === 0 // en==en-us
|| strpos($normalizedLanguage, $acceptableLanguage . '-') === 0 // en-us==en
) {
return $language;
}
}
}
return null;
}

/**
* Change the timezone of a datetime/timestamp
*
Expand Down

0 comments on commit 1f8bc98

Please sign in to comment.