parseAcceptLanguageHeader() public static method

This method only returns tags that conforms ISO 639 for language codes and ISO 3166 for region codes. HTTP spec (RFC 2616) defines both of these parts as 1*8ALPHA, but this method ignores tags with longer (or shorter) codes than defined in ISO mentioned above. There can be an asterisk "*" in the returned array, which means that any language is acceptable. Warning: This method expects that locale tags are placed in descending order by quality in the $header string. I'm not sure if it's always true with the web browsers.
public static parseAcceptLanguageHeader ( string $acceptLanguageHeader ) : mixed
$acceptLanguageHeader string
return mixed The array of locale identifiers or FALSE
コード例 #1
0
 /**
  * Returns best-matching Locale object based on the Accept-Language header
  * provided as parameter. System default locale will be returned if no
  * successful matches were done.
  *
  * @param string $acceptLanguageHeader The Accept-Language HTTP header
  * @return Locale Best-matching existing Locale instance
  * @api
  */
 public function detectLocaleFromHttpHeader($acceptLanguageHeader)
 {
     $acceptableLanguages = I18n\Utility::parseAcceptLanguageHeader($acceptLanguageHeader);
     if ($acceptableLanguages === false) {
         return $this->localizationService->getConfiguration()->getDefaultLocale();
     }
     foreach ($acceptableLanguages as $languageIdentifier) {
         if ($languageIdentifier === '*') {
             return $this->localizationService->getConfiguration()->getDefaultLocale();
         }
         try {
             $locale = new Locale($languageIdentifier);
         } catch (Exception\InvalidLocaleIdentifierException $exception) {
             continue;
         }
         $bestMatchingLocale = $this->localeCollection->findBestMatchingLocale($locale);
         if ($bestMatchingLocale !== null) {
             return $bestMatchingLocale;
         }
     }
     return $this->localizationService->getConfiguration()->getDefaultLocale();
 }
コード例 #2
0
 /**
  * @test
  * @dataProvider sampleHttpAcceptLanguageHeaders
  */
 public function httpAcceptLanguageHeadersAreParsedCorrectly($acceptLanguageHeader, array $expectedResult)
 {
     $languages = I18n\Utility::parseAcceptLanguageHeader($acceptLanguageHeader);
     $this->assertEquals($expectedResult, $languages);
 }