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
|
|
|
CsrfViewInjectionInterface |
15
|
|
|
{ |
16
|
|
|
public const DEFAULT_REQUEST_ATTRIBUTE = Csrf::REQUEST_NAME; |
17
|
|
|
public const DEFAULT_META_ATTRIBUTE = 'csrf'; |
18
|
|
|
public const DEFAULT_PARAMETER = 'csrf'; |
19
|
|
|
|
20
|
|
|
private UrlMatcherInterface $urlMatcher; |
21
|
|
|
|
22
|
|
|
private string $requestAttribute = self::DEFAULT_REQUEST_ATTRIBUTE; |
23
|
|
|
private string $metaAttribute = self::DEFAULT_META_ATTRIBUTE; |
24
|
|
|
private string $parameter = self::DEFAULT_PARAMETER; |
25
|
|
|
|
26
|
|
|
private ?string $csrfToken = null; |
27
|
|
|
|
28
|
|
|
public function __construct(UrlMatcherInterface $urlMatcher) |
29
|
|
|
{ |
30
|
|
|
$this->urlMatcher = $urlMatcher; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function withRequestAttribute(?string $requestAttribute = null): self |
34
|
|
|
{ |
35
|
|
|
$clone = clone $this; |
36
|
|
|
$clone->requestAttribute = $requestAttribute ?? self::DEFAULT_REQUEST_ATTRIBUTE; |
37
|
|
|
return $clone; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function withParameter(string $parameter): self |
41
|
|
|
{ |
42
|
|
|
$clone = clone $this; |
43
|
|
|
$clone->parameter = $parameter; |
44
|
|
|
return $clone; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function withMetaAttribute(string $metaAttribute): self |
48
|
|
|
{ |
49
|
|
|
$clone = clone $this; |
50
|
|
|
$clone->metaAttribute = $metaAttribute; |
51
|
|
|
return $clone; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function getContentParams(): array |
55
|
|
|
{ |
56
|
|
|
return [$this->parameter => $this->getCsrfToken()]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getLayoutParams(): array |
60
|
|
|
{ |
61
|
|
|
return [$this->parameter => $this->getCsrfToken()]; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function getMetaTags(): array |
65
|
|
|
{ |
66
|
|
|
return [ |
67
|
|
|
[ |
68
|
|
|
'__key' => 'csrf_meta_tags', |
69
|
|
|
'name' => $this->metaAttribute, |
70
|
|
|
'content' => $this->getCsrfToken(), |
71
|
|
|
] |
72
|
|
|
]; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function getCsrfToken(): string |
76
|
|
|
{ |
77
|
|
|
if ($this->csrfToken === null) { |
78
|
|
|
$this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute); |
79
|
|
|
} |
80
|
|
|
return $this->csrfToken; |
|
|
|
|
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|