Created
March 1, 2017 10:18
-
-
Save albe/2ffea7959d546b2b81d6a1bb37e24693 to your computer and use it in GitHub Desktop.
A Flow HTTP component for multilanguage
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 | |
namespace Acme\Foo\Http; | |
use TYPO3\Flow\Annotations as Flow; | |
use TYPO3\Flow\Http\Component\ComponentContext; | |
use TYPO3\Flow\Http\Component\ComponentInterface; | |
use TYPO3\Flow\I18n\Detector; | |
use TYPO3\Flow\I18n\Locale; | |
/** | |
* A HTTP component that detects and sets the current locale from request URI, cookie or Accept-Language header. | |
*/ | |
class DetectLanguageComponent implements ComponentInterface | |
{ | |
/** | |
* @Flow\Inject | |
* @var Detector | |
*/ | |
protected $localeDetector; | |
/** | |
* @Flow\Inject | |
* @var \TYPO3\Flow\I18n\Service | |
*/ | |
protected $i18nService; | |
/** | |
* @var array | |
*/ | |
protected $options; | |
protected static $defaultOptions = array( | |
'uriPosition' => 0, | |
'cookieName' => 'locale' | |
); | |
/** | |
* @param array $options The component options | |
*/ | |
public function __construct(array $options = array()) | |
{ | |
$this->options = array_merge(self::$defaultOptions, $options); | |
} | |
/** | |
* @param ComponentContext $componentContext | |
* @return void | |
*/ | |
public function handle(ComponentContext $componentContext) | |
{ | |
$httpRequest = $componentContext->getHttpRequest(); | |
$requestPath = $httpRequest->getUri()->getPath(); | |
$firstRequestPathSegment = explode('/', ltrim($requestPath, '/'))[$this->options['uriPosition']]; | |
if ($firstRequestPathSegment !== '') { | |
try { | |
$uriLocale = $this->localeDetector->detectLocaleFromTemplateLocale(new \TYPO3\Flow\I18n\Locale($firstRequestPathSegment)); | |
$this->i18nService->getConfiguration()->setCurrentLocale($uriLocale); | |
return; | |
} catch (\TYPO3\Flow\I18n\Exception\InvalidLocaleIdentifierException $exception) { | |
} | |
} | |
$localeCookie = $httpRequest->getCookie($this->options['cookieName']); | |
if ($localeCookie !== null) { | |
try { | |
$cookieLocale = $this->localeDetector->detectLocaleFromTemplateLocale(new \TYPO3\Flow\I18n\Locale($localeCookie)); | |
$this->i18nService->getConfiguration()->setCurrentLocale($cookieLocale); | |
return; | |
} catch (\TYPO3\Flow\I18n\Exception\InvalidLocaleIdentifierException $exception) { | |
} | |
} | |
$detectedLocale = $this->localeDetector->detectLocaleFromHttpHeader($httpRequest->getHeader('Accept-Language')); | |
if (!$detectedLocale instanceof Locale) { | |
return; | |
} | |
$this->i18nService->getConfiguration()->setCurrentLocale($detectedLocale); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment