Issues (26)

src/Html.php (1 issue)

Severity
1
<?php declare(strict_types = 1);
2
namespace Templado\Engine;
3
4
use DOMDocument;
5
use DOMDocumentType;
6
7
class Html {
8
9
    /** @var DOMDocument */
10
    private $dom;
11
12 24
    public function __construct(DOMDocument $dom) {
13 24
        $this->dom = $dom;
14 24
    }
15
16 3
    public function applySnippets(SnippetListCollection $snippetListCollection): void {
17 3
        (new SnippetRenderer($snippetListCollection))->render($this->dom->documentElement);
18 3
    }
19
20
    /**
21
     * @param object $model
22
     *
23
     * @throws ViewModelRendererException
24
     */
25 3
    public function applyViewModel($model): void {
26 3
        (new ViewModelRenderer())->render($this->dom->documentElement, $model);
27 3
    }
28
29
    /**
30
     * @throws FormDataRendererException
31
     */
32 3
    public function applyFormData(FormData $formData): void {
33 3
        (new FormDataRenderer())->render($this->dom->documentElement, $formData);
34 3
    }
35
36 3
    public function applyCSRFProtection(CSRFProtection $protection): void {
37 3
        (new CSRFProtectionRenderer())->render($this->dom->documentElement, $protection);
38 3
    }
39
40 3
    public function applyTransformation(Transformation $transformation): void {
41 3
        (new TransformationProcessor())->process($this->dom->documentElement, $transformation);
42 3
    }
43
44 9
    public function asString(Filter $filter = null): string {
45 9
        $content = $this->serializeDomDocument();
46 9
        $content = (new EmptyElementsFilter())->apply($content);
47 9
        $content = (new ClearNamespaceDefinitionsFilter())->apply($content);
48
49 9
        if ($filter === null) {
50 6
            return $content;
51
        }
52
53 3
        return $filter->apply($content);
54
    }
55
56 9
    private function serializeDomDocument(): string {
57 9
        $this->dom->formatOutput       = true;
58 9
        $this->dom->preserveWhiteSpace = false;
59
60 9
        $this->dom->loadXML(
61 9
            $this->dom->saveXML()
62
        );
63
64
        /** @psalm-suppress RedundantCondition psalm believes this cannot be null, but it can ;) */
65 9
        if ($this->dom->doctype instanceof DOMDocumentType) {
0 ignored issues
show
$this->dom->doctype is always a sub-type of DOMDocumentType.
Loading history...
66 3
            return $this->serializeWithoutXMLHeader();
67
        }
68
69 6
        return $this->dom->saveXML($this->dom->documentElement, \LIBXML_NOEMPTYTAG);
70
    }
71
72 3
    private function serializeWithoutXMLHeader(): string {
73 3
        return \implode(
74 3
            "\n",
75
            [
76 3
                $this->dom->saveXML($this->dom->doctype),
77 3
                $this->dom->saveXML($this->dom->documentElement, \LIBXML_NOEMPTYTAG)
78
            ]
79
        );
80
    }
81
}
82