Last active
August 29, 2015 14:02
-
-
Save arosemena/57ad4a08c0868a52c02d to your computer and use it in GitHub Desktop.
Simple class to check a client language from the HTTP headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class LangCheck | |
{ | |
private $default; | |
private $available; | |
/** | |
* @param array $available An array containing the available locales | |
* @param string $default The default language in case none is found | |
*/ | |
public function __construct($available = ['es'], $default = 'es') | |
{ | |
$this->default = $default; | |
$this->available = $available; | |
} | |
/** | |
* @return string Either the language stored on the cookie or Default | |
*/ | |
private function cookie() { | |
if(isset($_COOKIE['preferred_language'])) { | |
$preferred = $_COOKIE['preferred_language']; | |
if(in_array($preferred, $this->available)) { | |
return $preferred; | |
} | |
} | |
return "Default"; | |
} | |
/** | |
* The header is sent by most of the modern browsers, it looks something | |
* like this en-US,en;q=0.8,es;q=0.6, I ignore the q value because it's | |
* implicitly ordered by the browser | |
* | |
* @param string $header The HTTP header HTTP_ACCEPT_LANGUAGES from | |
* the global $_SERVER array | |
* @return string The 2 letter language identifier | |
*/ | |
public function get($header = "") | |
{ | |
$regex = '/([a-zA-Z]{2});/'; | |
$languages = []; | |
preg_match_all($regex, $header, $languages); | |
if($this->cookie() != 'Default') { | |
return $this->cookie(); | |
} | |
foreach($languages[1] as $language) { | |
if(in_array($language, $this->available)) { | |
return $language; | |
} | |
} | |
return $this->default; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment