1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace RazonYang\Yii\TranslatorMiddleware; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
10
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
11
|
|
|
use RazonYang\Yii\TranslatorMiddleware\Exception\InvalidTranslatorExcepction; |
12
|
|
|
use RazonYang\Yii\TranslatorMiddleware\Exception\TranslatorNotFoundExcepction; |
13
|
|
|
use Yiisoft\Translator\Translator; |
14
|
|
|
use Yiisoft\Translator\TranslatorInterface; |
15
|
|
|
|
16
|
|
|
class TranslatorMiddleware implements MiddlewareInterface |
17
|
|
|
{ |
18
|
3 |
|
public function __construct( |
19
|
|
|
private LocaleParserInterface $localeParser, |
20
|
|
|
private TranslatorInterface $translator, |
21
|
|
|
) { |
22
|
|
|
} |
23
|
|
|
|
24
|
3 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
25
|
|
|
{ |
26
|
3 |
|
$locale = $this->localeParser->parse($request) ?? $this->translator->getLocale(); |
27
|
3 |
|
$request = $request->withAttribute(self::class, $this->translator->withLocale($locale)); |
28
|
|
|
|
29
|
3 |
|
return $handler->handle($request); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Returns the translator instance from given request. |
34
|
|
|
* |
35
|
|
|
* @see getTranslatorFromAttributes |
36
|
|
|
*/ |
37
|
5 |
|
public static function getTranslator(ServerRequestInterface $request): TranslatorInterface |
38
|
|
|
{ |
39
|
5 |
|
return self::getTranslatorByAttributes($request->getAttributes()); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Returns the translator instance from given request attributes. |
44
|
|
|
* |
45
|
|
|
* @throws TranslatorNotFoundExcepction if no translator instace found. |
46
|
|
|
* @throws InvalidTranslatorExcepction if the translator instace with wrong type. |
47
|
|
|
* |
48
|
|
|
* @return TranslatorInterface |
49
|
|
|
*/ |
50
|
5 |
|
public static function getTranslatorByAttributes(array $attributes): TranslatorInterface |
51
|
|
|
{ |
52
|
5 |
|
if (!isset($attributes[self::class])) { |
53
|
1 |
|
throw new TranslatorNotFoundExcepction(); |
54
|
|
|
} |
55
|
|
|
|
56
|
4 |
|
$t = $attributes[self::class]; |
57
|
4 |
|
if (!($t instanceof TranslatorInterface)) { |
58
|
1 |
|
throw new InvalidTranslatorExcepction(); |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
return $t; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|