1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\ViewRenderer; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Router\UrlMatcherInterface; |
8
|
|
|
use Yiisoft\Yii\Web\Middleware\Csrf; |
9
|
|
|
|
10
|
|
|
class CsrfViewInjection implements |
11
|
|
|
ContentParamsInjectionInterface, |
12
|
|
|
LayoutParamsInjectionInterface, |
13
|
|
|
MetaTagsInjectionInterface |
14
|
|
|
{ |
15
|
|
|
public const DEFAULT_META_ATTRIBUTE = 'csrf'; |
16
|
|
|
public const DEFAULT_PARAMETER = 'csrf'; |
17
|
|
|
|
18
|
|
|
private UrlMatcherInterface $urlMatcher; |
19
|
|
|
|
20
|
|
|
private string $requestAttribute = Csrf::REQUEST_NAME; |
21
|
|
|
private string $metaAttribute = self::DEFAULT_META_ATTRIBUTE; |
22
|
|
|
private string $parameter = self::DEFAULT_PARAMETER; |
23
|
|
|
|
24
|
|
|
private ?string $csrfToken = null; |
25
|
|
|
|
26
|
|
|
public function __construct(UrlMatcherInterface $urlMatcher) |
27
|
|
|
{ |
28
|
|
|
$this->urlMatcher = $urlMatcher; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function withRequestAttribute(string $requestAttribute): self |
32
|
|
|
{ |
33
|
|
|
$clone = clone $this; |
34
|
|
|
$clone->requestAttribute = $requestAttribute; |
35
|
|
|
return $clone; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function withParameter(string $parameter): self |
39
|
|
|
{ |
40
|
|
|
$clone = clone $this; |
41
|
|
|
$clone->parameter = $parameter; |
42
|
|
|
return $clone; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function withMetaAttribute(string $metaAttribute): self |
46
|
|
|
{ |
47
|
|
|
$clone = clone $this; |
48
|
|
|
$clone->metaAttribute = $metaAttribute; |
49
|
|
|
return $clone; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function getContentParams(): array |
53
|
|
|
{ |
54
|
|
|
return [$this->parameter => $this->getCsrfToken()]; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function getLayoutParams(): array |
58
|
|
|
{ |
59
|
|
|
return [$this->parameter => $this->getCsrfToken()]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function getMetaTags(): array |
63
|
|
|
{ |
64
|
|
|
return [ |
65
|
|
|
[ |
66
|
|
|
'__key' => 'csrf_meta_tags', |
67
|
|
|
'name' => $this->metaAttribute, |
68
|
|
|
'content' => $this->getCsrfToken(), |
69
|
|
|
] |
70
|
|
|
]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
private function getCsrfToken(): string |
74
|
|
|
{ |
75
|
|
|
if ($this->csrfToken === null) { |
76
|
|
|
$this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute); |
77
|
|
|
} |
78
|
|
|
return $this->csrfToken; |
|
|
|
|
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|