Add UA::getLocale()

This commit is contained in:
Kijin Sung 2020-07-05 20:21:44 +09:00
parent 154bddfd18
commit dfc1082c85
3 changed files with 33 additions and 10 deletions

View file

@ -301,18 +301,17 @@ class Context
{
$lang_type = $_COOKIE['lang_type'];
}
elseif(config('locale.auto_select_lang') && count($enabled_langs) > 1)
elseif(config('locale.auto_select_lang') && count($enabled_langs) > 1 && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
{
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
$ua_locale = Rhymix\Framework\UA::getLocale();
if (substr($ua_locale, 0, 2) !== 'zh')
{
foreach($enabled_langs as $lang_code => $lang_name)
{
if(!strncasecmp($lang_code, $_SERVER['HTTP_ACCEPT_LANGUAGE'], strlen($lang_code)))
{
$lang_type = $lang_code;
$set_lang_cookie = true;
}
}
$ua_locale = substr($ua_locale, 0, 2);
}
if (isset($enabled_langs[$ua_locale]))
{
$lang_type = $ua_locale;
$set_lang_cookie = true;
}
}

View file

@ -177,6 +177,21 @@ class UA
return self::$_robot_cache[$ua] = false;
}
/**
* This method parses the Accept-Language header to guess the browser's default locale.
*
* @param string $header (optional)
* @return string
*/
public static function getLocale($header = null)
{
// Get the Accept-Language header if the caller did not specify $header.
$header = $header ?: (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en-US');
// Return the first locale name found.
return preg_match('/^([a-z0-9_-]+)/i', $header, $matches) ? $matches[1] : 'en-US';
}
/**
* This method parses the User-Agent string to guess what kind of browser it is.
*

View file

@ -47,6 +47,15 @@ class UATest extends \Codeception\TestCase\Test
$this->assertFalse(Rhymix\Framework\UA::isRobot('Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'));
}
public function testGetLocale()
{
$locale = Rhymix\Framework\UA::getLocale('en-US,en;q=0.8,ko-KR;q=0.5,ko;q=0.3');
$this->assertEquals('en-US', $locale);
$locale = Rhymix\Framework\UA::getLocale('ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3');
$this->assertEquals('ko-KR', $locale);
}
public function testGetBrowserInfo()
{
// Android default browser