Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
14 / 14 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| LocaleResolver | |
100.00% |
14 / 14 |
|
100.00% |
4 / 4 |
8 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| run | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| setLocaleViaAcceptLanguage | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| setLocaleViaParameter | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Dynart\Micro\Middleware; |
| 4 | |
| 5 | use Dynart\Micro\MiddlewareInterface; |
| 6 | use Dynart\Micro\RequestInterface; |
| 7 | use Dynart\Micro\RouterInterface; |
| 8 | use Dynart\Micro\TranslationInterface; |
| 9 | |
| 10 | class LocaleResolver implements MiddlewareInterface { |
| 11 | |
| 12 | protected int $localeRouteSegment; |
| 13 | |
| 14 | public function __construct( |
| 15 | protected RequestInterface $request, |
| 16 | protected RouterInterface $router, |
| 17 | protected TranslationInterface $translation |
| 18 | ) {} |
| 19 | |
| 20 | public function run(): void { |
| 21 | if (!$this->translation->hasMultiLocales()) { |
| 22 | return; |
| 23 | } |
| 24 | $this->localeRouteSegment = $this->router->addPrefixVariable([$this->translation, 'locale']); |
| 25 | $this->setLocaleViaAcceptLanguage(); |
| 26 | $this->setLocaleViaParameter(); |
| 27 | } |
| 28 | |
| 29 | protected function setLocaleViaAcceptLanguage(): void { |
| 30 | $acceptLanguage = $this->request->server('HTTP_ACCEPT_LANGUAGE'); |
| 31 | if ($acceptLanguage) { |
| 32 | $acceptLocale = strtolower(substr($acceptLanguage, 0, 2)); // we use only neutral locale for now |
| 33 | if (in_array($acceptLocale, $this->translation->allLocales())) { |
| 34 | $this->translation->setLocale($acceptLocale); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | protected function setLocaleViaParameter(): void { |
| 40 | $locale = $this->router->currentSegment($this->localeRouteSegment); |
| 41 | if (in_array($locale, $this->translation->allLocales())) { |
| 42 | $this->translation->setLocale($locale); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | } |