Debian Codegraph @

tests/parser/ParserTestResultNormalizer.php

raw symbols SCIP
1 <?php
2
3 /**
4 * @ingroup Testing
5 */
6 class ParserTestResultNormalizer {
7 /** @var DOMDocument */
8 protected $doc;
9 /** @var DOMNode|null */
10 protected $body;
11 /** @var DOMXPath */
12 protected $xpath;
13 /** @var bool */
14 protected $invalid;
15
16 /**
17 * @param string $text
18 * @param string[] $funcs
19 * @return string
20 */
21 public static function normalize( $text, $funcs ) {
22 $norm = new self( $text );
23 if ( $norm->invalid ) {
24 return $text;
25 }
26 foreach ( $funcs as $func ) {
27 $norm->$func();
28 }
29 return $norm->serialize();
30 }
31
32 protected function __construct( $text ) {
33 $this->doc = new DOMDocument( '1.0', 'utf-8' );
34
35 // Parsing a supposedly-XHTML document with an XML parser is not
36 // guaranteed to give accurate results. For example, it may introduce
37 // differences in the number of line breaks in <pre> tags.
38 if ( !@$this->doc->loadXML( '<html><body>' . $text . '</body></html>' ) ) {
39 $this->invalid = true;
40 }
41
42 $this->xpath = new DOMXPath( $this->doc );
43 $this->body = $this->xpath->query( '//body' )->item( 0 );
44 }
45
46 protected function removeTbody() {
47 foreach ( $this->xpath->query( '//tbody' ) as $tbody ) {
48 while ( $tbody->firstChild ) {
49 $child = $tbody->firstChild;
50 $tbody->removeChild( $child );
51 $tbody->parentNode->insertBefore( $child, $tbody );
52 }
53 $tbody->parentNode->removeChild( $tbody );
54 }
55 }
56
57 /**
58 * The point of this function is to produce a normalized DOM in which
59 * Tidy's output matches the output of RemexHtml. Tidy both trims
60 * and pretty-prints, so this requires fairly aggressive treatment.
61 *
62 * In particular, note that Tidy converts <pre>x</pre> to <pre>\nx\n</pre>,
63 * which theoretically affects display since the second line break is not
64 * ignored by compliant HTML parsers.
65 *
66 * This function also removes empty elements, as does Tidy.
67 */
68 protected function trimWhitespace() {
69 foreach ( $this->xpath->query( '//text()' ) as $child ) {
70 if ( strtolower( $child->parentNode->nodeName ) === 'pre' ) {
71 // Just trim one line break from the start and end
72 if ( str_starts_with( $child->data, "\n" ) ) {
73 $child->data = substr( $child->data, 1 );
74 }
75 if ( str_ends_with( $child->data, "\n" ) ) {
76 $child->data = substr( $child->data, 0, -1 );
77 }
78 } else {
79 // Trim all whitespace
80 $child->data = trim( $child->data );
81 }
82 if ( $child->data === '' ) {
83 $child->parentNode->removeChild( $child );
84 }
85 }
86 }
87
88 /**
89 * Serialize the XML DOM for comparison purposes. This does not generate HTML.
90 * @return string
91 */
92 protected function serialize() {
93 return strtr( $this->doc->saveXML( $this->body ),
94 [ '<body>' => '', '</body>' => '' ] );
95 }
96 }