xref: /webtrees/tests/views/AbstractViewTest.php (revision 1270d2767576ed4a83917769b0ee3613e3b010bf)
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
28abstract class AbstractViewTest extends TestCase
29{
30    protected const EVIL_VALUE = '<script>evil()</script>';
31
32    /**
33     * Check the view runs without error and generates valid HTML
34     *
35     * @param array<string,array<int,mixed>>  $data
36     */
37    protected function doTestView(string $view, array $data): void
38    {
39        foreach ($this->cartesian($data) as $datum) {
40            $html = view($view, $datum);
41
42            $this->validateHTML($html);
43        }
44    }
45
46    /**
47     * @param array<string,array<int,mixed>> $input
48     *
49     * @return array<int,array<string,mixed>>
50     */
51    private function cartesian(array $input): array
52    {
53        $result = [[]];
54
55        foreach ($input as $key => $values) {
56            $append = [];
57
58            foreach ($result as $product) {
59                foreach ($values as $item) {
60                    $product[$key] = $item;
61                    $append[]      = $product;
62                }
63            }
64
65            $result = $append;
66        }
67
68        return $result;
69    }
70
71    protected function validateHtml(string $html): void
72    {
73        if (str_starts_with($html, '<!DOCTYPE html>')) {
74            $xml = $html;
75        } else {
76            $xml = '<!DOCTYPE html><html lang="en"><body>' . $html . '</body></html>';
77        }
78
79        $doc = new DOMDocument();
80        $doc->validateOnParse = true;
81
82        self::assertTrue($doc->loadXML($xml, LIBXML_PEDANTIC), $html);
83    }
84}
85