Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
65.00% covered (warning)
65.00%
13 / 20
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
CsrfFunction
65.00% covered (warning)
65.00%
13 / 20
66.67% covered (warning)
66.67%
2 / 3
9.10
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFunctionName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 functionBodyImpl
61.11% covered (warning)
61.11%
11 / 18
0.00% covered (danger)
0.00%
0 / 1
6.47
1<?php
2
3declare(strict_types=1);
4
5namespace PeServer\Core\Mvc\Template\Plugin;
6
7use PeServer\Core\Collection\Arr;
8use PeServer\Core\Html\HtmlDocument;
9use PeServer\Core\Mvc\Template\Plugin\TemplateFunctionBase;
10use PeServer\Core\Mvc\Template\Plugin\TemplatePluginArgument;
11use PeServer\Core\Web\WebSecurity;
12use PeServer\Core\Text;
13use PeServer\Core\Throws\NotImplementedException;
14
15/**
16 * CSRFトークン埋め込み。
17 */
18class 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}