| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
class ParserTestResultNormalizer { |
| 7 |
|
| 8 |
protected $doc; |
| 9 |
|
| 10 |
protected $body; |
| 11 |
|
| 12 |
protected $xpath; |
| 13 |
|
| 14 |
protected $invalid; |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 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 |
|
| 36 |
|
| 37 |
|
| 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 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
protected function trimWhitespace() { |
| 69 |
foreach ( $this->xpath->query( '//text()' ) as $child ) { |
| 70 |
if ( strtolower( $child->parentNode->nodeName ) === 'pre' ) { |
| 71 |
|
| 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 |
|
| 80 |
$child->data = trim( $child->data ); |
| 81 |
} |
| 82 |
if ( $child->data === '' ) { |
| 83 |
$child->parentNode->removeChild( $child ); |
| 84 |
} |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
protected function serialize() { |
| 93 |
return strtr( $this->doc->saveXML( $this->body ), |
| 94 |
[ '<body>' => '', '</body>' => '' ] ); |
| 95 |
} |
| 96 |
} |