| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\RemexHtml\Tokenizer; |
| 4 |
|
| 5 |
/** |
| 6 |
* A simple serializer for the token stream, mostly meant for debugging. |
| 7 |
* |
| 8 |
* The main reason this shouldn't be used in production for modification of |
| 9 |
* HTML documents is that element names are only determined by TreeBuilder |
| 10 |
* and are not known here. The correct serialization for a text node depends |
| 11 |
* on its parent element, including its namespace. |
| 12 |
*/ |
| 13 |
class TokenSerializer implements TokenHandler { |
| 14 |
/** @var string */ |
| 15 |
private $output; |
| 16 |
/** @var array[] */ |
| 17 |
private $errors = []; |
| 18 |
|
| 19 |
/** |
| 20 |
* @return string |
| 21 |
*/ |
| 22 |
public function getOutput() { |
| 23 |
return $this->output; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* @return array[] |
| 28 |
*/ |
| 29 |
public function getErrors() { |
| 30 |
return $this->errors; |
| 31 |
} |
| 32 |
|
| 33 |
/** @inheritDoc */ |
| 34 |
public function startDocument( Tokenizer $tokenizer, $fns, $fn ) { |
| 35 |
$this->output = ''; |
| 36 |
} |
| 37 |
|
| 38 |
/** @inheritDoc */ |
| 39 |
public function endDocument( $pos ) { |
| 40 |
} |
| 41 |
|
| 42 |
/** @inheritDoc */ |
| 43 |
public function error( $text, $pos ) { |
| 44 |
$this->errors[] = [ $text, $pos ]; |
| 45 |
} |
| 46 |
|
| 47 |
/** @inheritDoc */ |
| 48 |
public function characters( $text, $start, $length, $sourceStart, $sourceLength ) { |
| 49 |
$this->output .= htmlspecialchars( substr( $text, $start, $length ) ); |
| 50 |
} |
| 51 |
|
| 52 |
/** @inheritDoc */ |
| 53 |
public function startTag( $name, Attributes $attrs, $selfClose, $sourceStart, $sourceLength ) { |
| 54 |
$attrs = $attrs->getValues(); |
| 55 |
$this->output .= "<$name"; |
| 56 |
foreach ( $attrs as $name => $value ) { |
| 57 |
$this->output .= " $name=\"" . str_replace( '"', '"', $value ) . '"'; |
| 58 |
} |
| 59 |
if ( $selfClose ) { |
| 60 |
$this->output .= ' /'; |
| 61 |
} |
| 62 |
$this->output .= '>'; |
| 63 |
} |
| 64 |
|
| 65 |
/** @inheritDoc */ |
| 66 |
public function endTag( $name, $sourceStart, $sourceLength ) { |
| 67 |
$this->output .= "</$name>"; |
| 68 |
} |
| 69 |
|
| 70 |
/** @inheritDoc */ |
| 71 |
public function doctype( $name, $public, $system, $quirks, $sourceStart, $sourceLength ) { |
| 72 |
$this->output .= "<!DOCTYPE $name"; |
| 73 |
if ( strlen( $public ) ) { |
| 74 |
$this->output .= " PUBLIC \"$public\""; |
| 75 |
if ( strlen( $system ) ) { |
| 76 |
$this->output .= " \"$system\""; |
| 77 |
} |
| 78 |
} elseif ( strlen( $system ) ) { |
| 79 |
$this->output .= " SYSTEM \"$system\""; |
| 80 |
} |
| 81 |
$this->output .= '>'; |
| 82 |
if ( $quirks ) { |
| 83 |
$this->output .= '<!--quirks-->'; |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
/** @inheritDoc */ |
| 88 |
public function comment( $text, $sourceStart, $sourceLength ) { |
| 89 |
$this->output .= '<!--' . $text . '-->'; |
| 90 |
} |
| 91 |
} |