i18n: Improve language detection

This commit is contained in:
loblao 2016-09-05 11:03:19 -03:00 committed by Alex Grintsvayg
parent 0c9e7724af
commit 982ffa1f51

View file

@ -14,32 +14,47 @@ class i18n
$language = null, $language = null,
$translations = [], $translations = [],
$country = null, $country = null,
$cultures = ['pt_PT', 'en_US']; $cultures = ['pt_PT', 'en_US'],
$subdomainToCulture = array(
'pt' => 'pt_PT',
'en' => 'en_US'
);
public static function register($culture = null) /*needed to trigger class include, presumably setup would happen here*/ public static function register($culture = null) /*needed to trigger class include, presumably setup would happen here*/
{ {
// Get user preference, if any // Get user preference, if any
if ($culture == null) if ($culture === null)
{ {
$culture = Session::get(Session::KEY_USER_CULTURE); $culture = Session::get(Session::KEY_USER_CULTURE);
} }
// Deduce from host // Deduce from subdomain
if ($culture === null) if ($culture === null)
{ {
$urlTokens = Request::getHost() ? explode('.', Request::getHost()) : []; $urlTokens = Request::getHost() ? explode('.', Request::getHost()) : [];
$code = $urlTokens ? reset($urlTokens) : 'en'; $code = $urlTokens ? reset($urlTokens) : 'en';
switch($code) if (in_array($code, static::$subdomainToCulture))
{ {
case 'pt': $culture = static::$subdomainToCulture[$code];
$culture = 'pt_PT'; break;
case 'en':
case 'www':
default:
$culture = 'en_US';
} }
} }
// Deduce from HTTP_ACCEPT_LANGUAGE
if ($culture === null)
{
$code = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($code, static::$cultures))
{
$culture = $code;
}
}
// Default to en_US
if ($culture === null)
{
$culture = 'en_US';
}
list($language, $country) = explode('_', $culture); list($language, $country) = explode('_', $culture);
static::$language = $language; static::$language = $language;
static::$country = $country; static::$country = $country;