Neos\Flow\I18n\Detector::detectLocaleFromHttpHeader PHP Method

detectLocaleFromHttpHeader() public method

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.
public detectLocaleFromHttpHeader ( string $acceptLanguageHeader ) : Locale
$acceptLanguageHeader string The Accept-Language HTTP header
return Locale Best-matching existing Locale instance
    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();
    }

Usage Example

 /**
  * @test
  * @dataProvider sampleHttpAcceptLanguageHeaders
  */
 public function detectingBestMatchingLocaleFromHttpAcceptLanguageHeaderWorksCorrectly($acceptLanguageHeader, $expectedResult)
 {
     $locale = $this->detector->detectLocaleFromHttpHeader($acceptLanguageHeader);
     $this->assertEquals($expectedResult, $locale);
 }