Passed
Pull Request — master (#10)
by Rustam
02:20
created

Locale::parseLocale()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.5923

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
nc 3
nop 1
dl 0
loc 9
ccs 4
cts 6
cp 0.6667
crap 4.5923
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Middleware;
6
7
use DateInterval;
8
use Psr\Http\Message\ResponseFactoryInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use Psr\Http\Server\MiddlewareInterface;
12
use Psr\Http\Server\RequestHandlerInterface;
13
use Psr\Log\LoggerInterface;
14
use Yiisoft\Cookies\Cookie;
15
use Yiisoft\Http\Header;
16
use Yiisoft\Http\Method;
17
use Yiisoft\Http\Status;
18
use Yiisoft\Router\UrlGeneratorInterface;
19
use Yiisoft\Session\SessionInterface;
20
use Yiisoft\Translator\TranslatorInterface;
21
22
final class Locale implements MiddlewareInterface
23
{
24
    private const DEFAULT_LOCALE = 'en';
25
    private const DEFAULT_LOCALE_NAME = '_language';
26
27
    private bool $enableSaveLocale = true;
28
    private bool $enableDetectLocale = false;
29
    private string $defaultLocale = self::DEFAULT_LOCALE;
30
    private string $queryParameterName = self::DEFAULT_LOCALE_NAME;
31
    private string $sessionName = self::DEFAULT_LOCALE_NAME;
32
    private ?DateInterval $cookieDuration;
33
34 6
    public function __construct(
35
        private TranslatorInterface $translator,
36
        private UrlGeneratorInterface $urlGenerator,
37
        private SessionInterface $session,
38
        private LoggerInterface $logger,
39
        private ResponseFactoryInterface $responseFactory,
40
        private array $locales = [],
41
        private bool $cookieSecure = false
42
    ) {
43 6
        $this->cookieDuration = new DateInterval('P30D');
44
    }
45
46 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
47
    {
48 5
        if ($this->locales === []) {
49 1
            return $handler->handle($request);
50
        }
51
52 4
        $uri = $request->getUri();
53 4
        $path = $uri->getPath();
54 4
        [$locale, $country] = $this->getLocaleFromPath($path);
55
56 4
        if ($locale !== null) {
57 2
            $response = $handler->handle($request);
58 2
            $newPath = null;
59 2
            if ($this->isDefaultLocale($locale, $country) && $request->getMethod() === Method::GET) {
60
                $length = strlen($locale);
61
                $newPath = substr($path, $length + 1);
62
            }
63 2
            return $this->applyLocaleFromPath($locale, $response, $newPath);
64
        }
65 2
        if ($this->enableSaveLocale) {
66 2
            [$locale, $country] = $this->getLocaleFromRequest($request);
67
        }
68 2
        if ($locale === null && $this->enableDetectLocale) {
69 1
            [$locale, $country] = $this->detectLocale($request);
70
        }
71 2
        if ($locale === null || $this->isDefaultLocale($locale, $country)) {
72
            $this->urlGenerator->setDefaultArgument($this->queryParameterName, null);
73
            $request = $request->withUri($uri->withPath('/' . $this->defaultLocale . $path));
74
            return $handler->handle($request);
75
        }
76 2
        $this->urlGenerator->setDefaultArgument($this->queryParameterName, $locale);
77
78 2
        if ($request->getMethod() === Method::GET) {
79 2
            return $this->responseFactory
80 2
                ->createResponse(Status::FOUND)
81 2
                ->withHeader(Header::LOCATION, '/' . $locale . $path);
82
        }
83
84
        return $handler->handle($request);
85
    }
86
87 2
    private function applyLocaleFromPath(
88
        string $locale,
89
        ResponseInterface $response,
90
        ?string $newPath = null
91
    ): ResponseInterface {
92 2
        if ($newPath === '') {
93
            $newPath = '/';
94
        }
95 2
        $this->translator->setLocale($locale);
96 2
        $this->urlGenerator->setDefaultArgument($this->queryParameterName, $locale);
97
98 2
        if ($newPath !== null) {
99
            $response = $this->responseFactory
100
                ->createResponse(Status::FOUND)
101
                ->withHeader(Header::LOCATION, $newPath);
102
        }
103 2
        if ($this->enableSaveLocale) {
104 2
            $response = $this->saveLocale($locale, $response);
105
        }
106 2
        return $response;
107
    }
108
109 4
    private function getLocaleFromPath(string $path): array
110
    {
111 4
        $parts = [];
112 4
        foreach ($this->locales as $code => $locale) {
113 4
            $lang = is_string($code) ? $code : $locale;
114 4
            $parts[] = $lang;
115
        }
116
117 4
        $pattern = implode('|', $parts);
118 4
        if (preg_match("#^/($pattern)\b(/?)#i", $path, $matches)) {
119 2
            $locale = $matches[1];
120 2
            [$locale, $country] = $this->parseLocale($locale);
121 2
            if (isset($this->locales[$locale])) {
122 2
                $this->logger->info(sprintf("Locale '%s' found in URL", $locale));
123 2
                return [$locale, $country];
124
            }
125
        }
126 2
        return [null, null];
127
    }
128
129 2
    private function getLocaleFromRequest(ServerRequestInterface $request): array
130
    {
131 2
        $cookies = $request->getCookieParams();
132 2
        $queryParameters = $request->getQueryParams();
133 2
        if (isset($cookies[$this->sessionName])) {
134
            $this->logger->info(sprintf("Locale '%s' found in cookies", $cookies[$this->sessionName]));
135
            return $this->parseLocale($cookies[$this->sessionName]);
136
        }
137 2
        if (isset($queryParameters[$this->queryParameterName])) {
138 1
            $this->logger->info(
139 1
                sprintf("Locale '%s' found in query string", $queryParameters[$this->queryParameterName])
140
            );
141 1
            return $this->parseLocale($queryParameters[$this->queryParameterName]);
142
        }
143 1
        return [null, null];
144
    }
145
146 4
    private function isDefaultLocale(string $locale, ?string $country): bool
147
    {
148 4
        return $locale === $this->defaultLocale || ($country !== null && $this->defaultLocale === "$locale-$country");
149
    }
150
151 1
    private function detectLocale(ServerRequestInterface $request): array
152
    {
153 1
        foreach ($request->getHeader(Header::ACCEPT_LANGUAGE) as $language) {
154 1
            return $this->parseLocale($language);
155
        }
156
        return [null, null];
157
    }
158
159 2
    private function saveLocale(string $locale, ResponseInterface $response): ResponseInterface
160
    {
161 2
        $this->logger->info('Saving found locale to cookies');
162 2
        $this->session->set($this->sessionName, $locale);
163 2
        $cookie = new Cookie(name: $this->sessionName, value: $locale, secure: $this->cookieSecure);
164 2
        if ($this->cookieDuration !== null) {
165 2
            $cookie = $cookie->withMaxAge($this->cookieDuration);
166
        }
167 2
        return $cookie->addToResponse($response);
168
    }
169
170 4
    private function parseLocale(string $locale): array
171
    {
172 4
        if (str_contains($locale, '-')) {
173
            return explode('-', $locale, 2);
174
        }
175 4
        if (isset($this->locales[$locale]) && str_contains($this->locales[$locale], '-')) {
176 4
            return explode('-', $this->locales[$locale], 2);
177
        }
178
        return [$locale, null];
179
    }
180
181 1
    public function withLocales(array $locales): self
182
    {
183 1
        $new = clone $this;
184 1
        $new->locales = $locales;
185 1
        return $new;
186
    }
187
188 1
    public function withDefaultLocale(string $defaultLocale): self
189
    {
190 1
        $new = clone $this;
191 1
        $new->defaultLocale = $defaultLocale;
192 1
        return $new;
193
    }
194
195 1
    public function withQueryParameterName(string $queryParameterName): self
196
    {
197 1
        $new = clone $this;
198 1
        $new->queryParameterName = $queryParameterName;
199 1
        return $new;
200
    }
201
202 1
    public function withSessionName(string $sessionName): self
203
    {
204 1
        $new = clone $this;
205 1
        $new->sessionName = $sessionName;
206 1
        return $new;
207
    }
208
209 1
    public function withEnableSaveLocale(bool $enableSaveLocale): self
210
    {
211 1
        $new = clone $this;
212 1
        $new->enableDetectLocale = $enableSaveLocale;
213 1
        return $new;
214
    }
215
216 2
    public function withEnableDetectLocale(bool $enableDetectLocale): self
217
    {
218 2
        $new = clone $this;
219 2
        $new->enableDetectLocale = $enableDetectLocale;
220 2
        return $new;
221
    }
222
223 1
    public function withCookieSecure(bool $secure): self
224
    {
225 1
        $new = clone $this;
226 1
        $new->cookieSecure = $secure;
227 1
        return $new;
228
    }
229
}
230