Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| LocaleContextBuilder | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
6 | |
100.00% |
1 / 1 |
| process | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
6 | |||
| 1 | <?php |
| 2 | namespace Apie\Common\ContextBuilders; |
| 3 | |
| 4 | use Apie\Core\Context\ApieContext; |
| 5 | use Apie\Core\ContextBuilders\ContextBuilderInterface; |
| 6 | use Apie\Core\ContextConstants; |
| 7 | use Apie\Core\Utils\LanguageParser; |
| 8 | use Psr\Http\Message\ServerRequestInterface; |
| 9 | |
| 10 | /** |
| 11 | * Context builder that reads the Accept-Language and Content-Language headers and adds them to the context. |
| 12 | */ |
| 13 | class LocaleContextBuilder implements ContextBuilderInterface |
| 14 | { |
| 15 | public function process(ApieContext $context): ApieContext |
| 16 | { |
| 17 | $request = $context->getContext(ServerRequestInterface::class, false); |
| 18 | if ($request instanceof ServerRequestInterface) { |
| 19 | $acceptLanguage = $request->getHeaderLine('Accept-Language'); |
| 20 | if ($acceptLanguage) { |
| 21 | $locales = LanguageParser::parseLanguageHeader($acceptLanguage); |
| 22 | if (!empty($locales)) { |
| 23 | $context = $context->withContext(ContextConstants::ACCEPT_LOCALE, $locales[0]); |
| 24 | $context = $context->withContext(ContextConstants::ACCEPTED_LOCALES, $locales); |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | $contentLanguage = $request->getHeaderLine('Content-Language'); |
| 29 | if ($contentLanguage) { |
| 30 | $locales = LanguageParser::parseLanguageHeader($contentLanguage); |
| 31 | if (!empty($locales)) { |
| 32 | $context = $context->withContext(ContextConstants::LOCALE, $locales[0]); |
| 33 | $context = $context->withContext(ContextConstants::DATA_LOCALE, $locales[0]); |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | return $context; |
| 38 | } |
| 39 | } |