1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2021 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; 23use Exception; 24 25use function str_starts_with; 26 27use const LIBXML_PEDANTIC; 28 29/** 30 * Common functions for testing views 31 */ 32abstract class AbstractViewTest extends TestCase 33{ 34 protected const EVIL_VALUE = '<script>evil()</script>'; 35 36 /** 37 * Check the view runs without error and generates valid HTML 38 * 39 * @param string $view 40 * @param array<array<string,array<string,mixed>> $data 41 */ 42 protected function doTestView(string $view, array $data): void 43 { 44 foreach ($this->cartesian($data) as $datum) { 45 $html = view($view, $datum); 46 47 $this->validateHTML($html); 48 } 49 } 50 51 /** 52 * @param array<string,array<string,mixed>> $input 53 * 54 * @return array<array<string,array<string,mixed>> 55 */ 56 private function cartesian(array $input): array 57 { 58 $result = [[]]; 59 60 foreach ($input as $key => $values) { 61 $append = []; 62 63 foreach ($result as $product) { 64 foreach ($values as $item) { 65 $product[$key] = $item; 66 $append[] = $product; 67 } 68 } 69 70 $result = $append; 71 } 72 73 return $result; 74 } 75 76 /** 77 * @param string $html 78 */ 79 private function validateHTML(string $html): void 80 { 81 if (str_starts_with($html, '<!DOCTYPE html>')) { 82 $xml = $html; 83 } else { 84 $xml = '<!DOCTYPE html><html lang="en"><body>' . $html . '</body></html>'; 85 } 86 87 $doc = new DOMDocument(); 88 $doc->validateOnParse = true; 89 90 try { 91 self::assertTrue($doc->loadXML($xml, LIBXML_PEDANTIC), $html); 92 } catch (Exception $ex) { 93 echo $html, PHP_EOL; 94 self::assertTrue(false); 95 } 96 } 97} 98