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

CsrfInjection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
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 withConfig(array $config): self
32
    {
33
        $clone = clone $this;
34
        $clone->requestAttribute = $config['requestAttribute'] ?? Csrf::REQUEST_NAME;
35
        $clone->metaAttribute = $config['metaAttribute'] ?? self::DEFAULT_META_ATTRIBUTE;
36
        $clone->parameter = $config['parameter'] ?? self::DEFAULT_PARAMETER;
37
        return $clone;
38
    }
39
40
    public function getParams(): array
41
    {
42
        $csrfToken = $this->getCsrfToken();
43
44
        $this->view->registerMetaTag(
45
            [
46
                'name' => $this->metaAttribute,
47
                'content' => $this->csrfToken,
48
            ],
49
            'csrf_meta_tags'
50
        );
51
52
        return [$this->parameter => $csrfToken];
53
    }
54
55
    private ?string $csrfToken = null;
56
57
    private function getCsrfToken(): string
58
    {
59
        if ($this->csrfToken === null) {
60
            $this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute);
61
        }
62
        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...
63
    }
64
}
65