Passed
Pull Request — master (#122)
by
unknown
19:32 queued 04:35
created

CsrfViewInjection::getCsrfToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
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;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->csrfToken could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
79
    }
80
}
81