Passed
Pull Request — master (#122)
by
unknown
14:32
created

CsrfViewInjection::getLayoutParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
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
    public function __construct(UrlMatcherInterface $urlMatcher)
25
    {
26
        $this->urlMatcher = $urlMatcher;
27
    }
28
29
    public function withRequestAttribute(string $requestAttribute): self
30
    {
31
        $clone = clone $this;
32
        $clone->requestAttribute = $requestAttribute;
33
        return $clone;
34
    }
35
36
    public function withParameter(string $parameter): self
37
    {
38
        $clone = clone $this;
39
        $clone->parameter = $parameter;
40
        return $clone;
41
    }
42
43
    public function withMetaAttribute(string $metaAttribute): self
44
    {
45
        $clone = clone $this;
46
        $clone->metaAttribute = $metaAttribute;
47
        return $clone;
48
    }
49
50
    public function getContentParams(): array
51
    {
52
        return [$this->parameter => $this->getCsrfToken()];
53
    }
54
55
    public function getLayoutParams(): array
56
    {
57
        return [$this->parameter => $this->getCsrfToken()];
58
    }
59
60
    public function getMetaTags(): array
61
    {
62
        return [
63
            [
64
                '__key' => 'csrf_meta_tags',
65
                'name' => $this->metaAttribute,
66
                'content' => $this->getCsrfToken(),
67
            ]
68
        ];
69
    }
70
71
    private ?string $csrfToken = null;
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