xref: /webtrees/tests/views/AbstractViewTest.php (revision 202c018b592d5a516e4a465dc6dc515f3be37399)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use DOMDocument;
23
24use function str_starts_with;
25
26use const LIBXML_PEDANTIC;
27
28
29abstract class AbstractViewTest extends TestCase
30{
31    protected const EVIL_VALUE = '<script>evil()</script>';
32
33    /**
34     * Check the view runs without error and generates valid HTML
35     *
36     * @param array<string,array<int,mixed>>  $data
37     */
38    protected function doTestView(string $view, array $data): void
39    {
40        foreach ($this->cartesian($data) as $datum) {
41            $html = view($view, $datum);
42
43            $this->validateHTML($html);
44        }
45    }
46
47    /**
48     * @param array<string,array<int,mixed>> $input
49     *
50     * @return array<int,array<string,mixed>>
51     */
52    private function cartesian(array $input): array
53    {
54        $result = [[]];
55
56        foreach ($input as $key => $values) {
57            $append = [];
58
59            foreach ($result as $product) {
60                foreach ($values as $item) {
61                    $product[$key] = $item;
62                    $append[]      = $product;
63                }
64            }
65
66            $result = $append;
67        }
68
69        return $result;
70    }
71
72    protected function validateHTML(string $html): void
73    {
74        if (str_starts_with($html, '<!DOCTYPE html>')) {
75            $xml = $html;
76        } else {
77            $xml = '<!DOCTYPE html><html lang="en"><body>' . $html . '</body></html>';
78        }
79
80        $doc = new DOMDocument();
81        $doc->validateOnParse = true;
82
83        self::assertTrue($doc->loadXML($xml, LIBXML_PEDANTIC), $html);
84    }
85}
86