1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\Endpoint\Web\Middleware; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
|
|
|
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
|
|
|
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
|
|
|
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
|
|
|
11
|
|
|
use Spiral\Translator\Translator; |
|
|
|
|
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The middleware that sets the application locale based on the "Accept-Language" header. |
15
|
|
|
* List of available locales is taken from the translator. |
16
|
|
|
*/ |
17
|
|
|
final class LocaleSelector implements MiddlewareInterface |
18
|
|
|
{ |
19
|
|
|
/** @var string[] */ |
20
|
|
|
private array $availableLocales; |
21
|
|
|
|
22
|
|
|
public function __construct( |
23
|
|
|
private readonly Translator $translator, |
24
|
|
|
) { |
25
|
|
|
$this->availableLocales = $this->translator->getCatalogueManager()->getLocales(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
29
|
|
|
{ |
30
|
|
|
$defaultLocale = $this->translator->getLocale(); |
31
|
|
|
|
32
|
|
|
try { |
33
|
|
|
foreach ($this->fetchLocales($request) as $locale) { |
34
|
|
|
if ($locale !== '' && \in_array($locale, $this->availableLocales, true)) { |
35
|
|
|
$this->translator->setLocale($locale); |
36
|
|
|
break; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $handler->handle($request); |
41
|
|
|
} finally { |
42
|
|
|
// restore |
43
|
|
|
$this->translator->setLocale($defaultLocale); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function fetchLocales(ServerRequestInterface $request): \Generator |
48
|
|
|
{ |
49
|
|
|
$header = $request->getHeaderLine('accept-language'); |
50
|
|
|
foreach (\explode(',', $header) as $value) { |
51
|
|
|
$pos = \strpos($value, ';'); |
52
|
|
|
if ($pos !== false) { |
53
|
|
|
yield \substr($value, 0, $pos); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
yield $value; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"]
, you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths