Passed
Pull Request — master (#122)
by
unknown
10:47
created

CsrfInjection   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 29
c 1
b 0
f 0
dl 0
loc 64
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A withParameter() 0 5 1
A withMetaAttribute() 0 5 1
A getCsrfToken() 0 6 2
A withRequestAttribute() 0 5 1
A getParams() 0 13 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\ViewRenderer;
6
7
use Yiisoft\Router\UrlMatcherInterface;
8
use Yiisoft\View\WebView;
9
use Yiisoft\Yii\Web\Middleware\Csrf;
10
11
class CsrfInjection implements InjectionInterface
12
{
13
    public const DEFAULT_META_ATTRIBUTE = 'csrf';
14
    public const DEFAULT_PARAMETER = 'csrf';
15
16
    private UrlMatcherInterface $urlMatcher;
17
    private WebView $view;
18
19
    private string $requestAttribute = Csrf::REQUEST_NAME;
20
    private string $metaAttribute = self::DEFAULT_META_ATTRIBUTE;
21
    private string $parameter = self::DEFAULT_PARAMETER;
22
23
    public function __construct(
24
        UrlMatcherInterface $urlMatcher,
25
        WebView $view
26
    ) {
27
        $this->urlMatcher = $urlMatcher;
28
        $this->view = $view;
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 getParams(): array
53
    {
54
        $csrfToken = $this->getCsrfToken();
55
56
        $this->view->registerMetaTag(
57
            [
58
                'name' => $this->metaAttribute,
59
                'content' => $this->csrfToken,
60
            ],
61
            'csrf_meta_tags'
62
        );
63
64
        return [$this->parameter => $csrfToken];
65
    }
66
67
    private ?string $csrfToken = null;
68
69
    private function getCsrfToken(): string
70
    {
71
        if ($this->csrfToken === null) {
72
            $this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute);
73
        }
74
        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...
75
    }
76
}
77