Checks if the types of returned expressions are compatible with the hinted types.
1 | <?php declare(strict_types = 1); |
||
2 | namespace Templado\Engine; |
||
3 | |||
4 | use DOMElement; |
||
5 | use DOMXPath; |
||
6 | |||
7 | /** @psalm-suppress MissingConstructor */ |
||
8 | class CSRFProtectionRenderer { |
||
9 | |||
10 | /** @var CSRFProtection */ |
||
11 | private $protection; |
||
12 | |||
13 | /** @var DOMXPath */ |
||
14 | private $xp; |
||
15 | |||
16 | 12 | public function render(DOMElement $context, CSRFProtection $protection): void { |
|
17 | 12 | $this->protection = $protection; |
|
18 | 12 | $this->xp = new DOMXPath($context->ownerDocument); |
|
19 | |||
20 | 12 | foreach ($context->getElementsByTagName('form') as $form) { |
|
21 | 12 | $this->getCSRFField($form)->setAttribute( |
|
22 | 12 | 'value', |
|
23 | 12 | $protection->getTokenValue() |
|
24 | ); |
||
25 | } |
||
26 | 12 | } |
|
27 | |||
28 | 12 | private function getCSRFField(DOMElement $form): DOMElement { |
|
29 | 12 | $nodeList = $this->xp->query( |
|
30 | 12 | \sprintf('.//*[local-name() = "input" and @name="%s"]', $this->protection->getFieldName()), |
|
31 | 4 | $form |
|
32 | ); |
||
33 | |||
34 | 12 | if ($nodeList->length === 0) { |
|
35 | 6 | return $this->createField($form); |
|
36 | } |
||
37 | |||
38 | /** @psalm-var \DOMElement */ |
||
39 | 6 | return $nodeList->item(0); |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
40 | } |
||
41 | |||
42 | 6 | private function createField(DOMElement $form): DOMElement { |
|
43 | 6 | if ($form->namespaceURI !== null) { |
|
44 | 3 | $input = $form->ownerDocument->createElementNS($form->namespaceURI, 'input'); |
|
45 | } else { |
||
46 | 3 | $input = $form->ownerDocument->createElement('input'); |
|
47 | } |
||
48 | |||
49 | 6 | $form->insertBefore($input, $form->firstChild); |
|
50 | 6 | $input->setAttribute('type', 'hidden'); |
|
51 | 6 | $input->setAttribute('name', $this->protection->getFieldName()); |
|
52 | |||
53 | 6 | return $input; |
|
54 | } |
||
55 | } |
||
56 |