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