CakeRequest::acceptLanguage PHP Method

acceptLanguage() public static method

Get the list of accepted languages: CakeRequest::acceptLanguage(); Check if a specific language is accepted: CakeRequest::acceptLanguage('es-es');
public static acceptLanguage ( string $language = null ) : mixed
$language string The language to test.
return mixed If a $language is provided, a boolean. Otherwise the array of accepted languages.
    public static function acceptLanguage($language = null)
    {
        $raw = static::_parseAcceptWithQualifier(static::header('Accept-Language'));
        $accept = array();
        foreach ($raw as $languages) {
            foreach ($languages as &$lang) {
                if (strpos($lang, '_')) {
                    $lang = str_replace('_', '-', $lang);
                }
                $lang = strtolower($lang);
            }
            $accept = array_merge($accept, $languages);
        }
        if ($language === null) {
            return $accept;
        }
        return in_array(strtolower($language), $accept);
    }

Usage Example

Example #1
0
 /**
  * autoDetectLocale
  *
  * If a string or array of cancicates are provided  -loop over them
  * otherwise get the candiate locales from the accept-language header
  *
  * Loop over the possible locales, account for regional dialects and
  * set the currentrequest language to that locale, and return that value
  *
  * @param mixed $candidates
  * @return string matched language
  */
 public static function autoDetectLocale($candidates = null)
 {
     $locales = static::locales();
     if ($candidates) {
         if (is_string($candidates)) {
             $candidates = explode(',', $candidates);
         }
     } else {
         $candidates = CakeRequest::acceptLanguage();
     }
     $candidates = array_filter($candidates, function ($in) {
         return strpos($in, 'q=') === false;
     });
     $permutations = array();
     foreach ($candidates as $langKey) {
         if (strlen($langKey) === 5) {
             $permutations[] = substr($langKey, 0, 2) . '_' . strtoupper(substr($langKey, -2, 2));
         }
         $permutations[] = substr($langKey, 0, 2);
     }
     $permutations = array_unique($permutations);
     $match = false;
     foreach ($permutations as $langKey) {
         if (!empty($locales[$langKey])) {
             Configure::write('Config.language', $langKey);
             $match = $langKey;
             break;
         }
     }
     return $match;
 }
All Usage Examples Of CakeRequest::acceptLanguage