Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
65.00% |
13 / 20 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
CsrfFunction | |
65.00% |
13 / 20 |
|
66.67% |
2 / 3 |
9.10 | |
0.00% |
0 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getFunctionName | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
functionBodyImpl | |
61.11% |
11 / 18 |
|
0.00% |
0 / 1 |
6.47 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace PeServer\Core\Mvc\Template\Plugin; |
6 | |
7 | use PeServer\Core\Collection\Arr; |
8 | use PeServer\Core\Html\HtmlDocument; |
9 | use PeServer\Core\Mvc\Template\Plugin\TemplateFunctionBase; |
10 | use PeServer\Core\Mvc\Template\Plugin\TemplatePluginArgument; |
11 | use PeServer\Core\Web\WebSecurity; |
12 | use PeServer\Core\Text; |
13 | use PeServer\Core\Throws\NotImplementedException; |
14 | |
15 | /** |
16 | * CSRFトークン埋め込み。 |
17 | */ |
18 | class CsrfFunction extends TemplateFunctionBase |
19 | { |
20 | public function __construct(TemplatePluginArgument $argument) |
21 | { |
22 | parent::__construct($argument); |
23 | } |
24 | |
25 | #region TemplateFunctionBase |
26 | |
27 | public function getFunctionName(): string |
28 | { |
29 | return 'csrf'; |
30 | } |
31 | |
32 | protected function functionBodyImpl(): string |
33 | { |
34 | // このタイミングではセッション処理完了を期待している |
35 | |
36 | if (!$this->argument->stores->session->tryGet($this->argument->webSecurity->getCsrfKind(WebSecurity::CSRF_KIND_SESSION_KEY), $csrfToken)) { |
37 | return Text::EMPTY; |
38 | } |
39 | /** @var string $csrfToken */ |
40 | |
41 | /** @var string $type */ |
42 | $type = $this->params['type'] ?? 'name'; |
43 | |
44 | $dom = new HtmlDocument(); |
45 | |
46 | switch ($type) { |
47 | case 'id': |
48 | $element = $dom->addTagElement('meta'); |
49 | |
50 | $element->setAttribute('id', $this->argument->webSecurity->getCsrfKind(WebSecurity::CSRF_KIND_REQUEST_ID)); |
51 | $element->setAttribute('name', $this->argument->webSecurity->getCsrfKind(WebSecurity::CSRF_KIND_REQUEST_ID)); |
52 | $element->setAttribute('content', $csrfToken); |
53 | break; |
54 | |
55 | case 'name': |
56 | $element = $dom->addTagElement('input'); |
57 | |
58 | $element->setAttribute('type', 'hidden'); |
59 | $element->setAttribute('name', $this->argument->webSecurity->getCsrfKind(WebSecurity::CSRF_KIND_REQUEST_NAME)); |
60 | $element->setAttribute('value', $csrfToken); |
61 | break; |
62 | |
63 | default: |
64 | throw new NotImplementedException(); |
65 | } |
66 | |
67 | return $dom->build(); |
68 | } |
69 | |
70 | #endregion |
71 | } |