1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace App\ViewRenderer; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Router\UrlMatcherInterface; |
8
|
|
|
use Yiisoft\View\WebView; |
9
|
|
|
use Yiisoft\Yii\Web\Middleware\Csrf; |
10
|
|
|
|
11
|
|
|
class CsrfInjection implements InjectionInterface |
12
|
|
|
{ |
13
|
|
|
public const DEFAULT_META_ATTRIBUTE = 'csrf'; |
14
|
|
|
public const DEFAULT_PARAMETER = 'csrf'; |
15
|
|
|
|
16
|
|
|
private UrlMatcherInterface $urlMatcher; |
17
|
|
|
private WebView $view; |
18
|
|
|
|
19
|
|
|
private string $requestAttribute = Csrf::REQUEST_NAME; |
20
|
|
|
private string $metaAttribute = self::DEFAULT_META_ATTRIBUTE; |
21
|
|
|
private string $parameter = self::DEFAULT_PARAMETER; |
22
|
|
|
|
23
|
|
|
public function __construct( |
24
|
|
|
UrlMatcherInterface $urlMatcher, |
25
|
|
|
WebView $view |
26
|
|
|
) { |
27
|
|
|
$this->urlMatcher = $urlMatcher; |
28
|
|
|
$this->view = $view; |
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 getParams(): array |
53
|
|
|
{ |
54
|
|
|
$csrfToken = $this->getCsrfToken(); |
55
|
|
|
|
56
|
|
|
$this->view->registerMetaTag( |
57
|
|
|
[ |
58
|
|
|
'name' => $this->metaAttribute, |
59
|
|
|
'content' => $this->csrfToken, |
60
|
|
|
], |
61
|
|
|
'csrf_meta_tags' |
62
|
|
|
); |
63
|
|
|
|
64
|
|
|
return [$this->parameter => $csrfToken]; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
private ?string $csrfToken = null; |
68
|
|
|
|
69
|
|
|
private function getCsrfToken(): string |
70
|
|
|
{ |
71
|
|
|
if ($this->csrfToken === null) { |
72
|
|
|
$this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute); |
73
|
|
|
} |
74
|
|
|
return $this->csrfToken; |
|
|
|
|
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|