Passed
Pull Request — master (#122)
by
unknown
16:22 queued 01:22
created

CsrfInjection::withRequestAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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 CsrfInjection extends AbstractInjection
11
{
12
    public const DEFAULT_META_ATTRIBUTE = 'csrf';
13
    public const DEFAULT_PARAMETER = 'csrf';
14
15
    private UrlMatcherInterface $urlMatcher;
16
17
    private string $requestAttribute = Csrf::REQUEST_NAME;
18
    private string $metaAttribute = self::DEFAULT_META_ATTRIBUTE;
19
    private string $parameter = self::DEFAULT_PARAMETER;
20
21
    public function __construct(UrlMatcherInterface $urlMatcher)
22
    {
23
        $this->urlMatcher = $urlMatcher;
24
    }
25
26
    public function withRequestAttribute(string $requestAttribute): self
27
    {
28
        $clone = clone $this;
29
        $clone->requestAttribute = $requestAttribute;
30
        return $clone;
31
    }
32
33
    public function withParameter(string $parameter): self
34
    {
35
        $clone = clone $this;
36
        $clone->parameter = $parameter;
37
        return $clone;
38
    }
39
40
    public function withMetaAttribute(string $metaAttribute): self
41
    {
42
        $clone = clone $this;
43
        $clone->metaAttribute = $metaAttribute;
44
        return $clone;
45
    }
46
47
    public function getContentParams(): array
48
    {
49
        return [$this->parameter => $this->getCsrfToken()];
50
    }
51
52
    public function getLayoutParams(): array
53
    {
54
        return [$this->parameter => $this->getCsrfToken()];
55
    }
56
57
    public function getMetaTags(): array
58
    {
59
        return [
60
            [
61
                '__key' => 'csrf_meta_tags',
62
                'name' => $this->metaAttribute,
63
                'content' => $this->getCsrfToken(),
64
            ]
65
        ];
66
    }
67
68
    private ?string $csrfToken = null;
69
70
    private function getCsrfToken(): string
71
    {
72
        if ($this->csrfToken === null) {
73
            $this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute);
74
        }
75
        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...
76
    }
77
}
78