Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 114
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
HtmlFormatter
0.00% covered (danger)
0.00%
0 / 114
0.00% covered (danger)
0.00%
0 / 9
2756
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 isRawTextElement
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 startDocument
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 characters
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 element
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
56
 comment
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 doctype
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 formatDOMNode
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
306
 formatDOMElement
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
342
1<?php
2declare( strict_types = 1 );
3
4namespace Wikimedia\RemexHtml\Serializer;
5
6use Wikimedia\RemexHtml\DOM\DOMFormatter;
7use Wikimedia\RemexHtml\DOM\DOMUtils;
8use Wikimedia\RemexHtml\HTMLData;
9
10/**
11 * A formatter which follows the HTML 5 fragment serialization algorithm.
12 */
13class HtmlFormatter implements Formatter, DOMFormatter {
14    /**
15     * The elements for which a closing tag is omitted.
16     *
17     * @var array<string,bool>
18     * @deprecated Use HTMLData::TAGS['void'] instead.
19     */
20    protected $voidElements = HTMLData::TAGS['void'];
21
22    /**
23     * The elements which need a leading newline in their contents to be
24     * duplicated, since the parser strips a leading newline.
25     *
26     * @var array<string,bool>
27     * @deprecated Use HTMLData::TAGS['prefixLF'] instead.
28     */
29    protected $prefixLfElements = HTMLData::TAGS['prefixLF'];
30
31    /**
32     * The elements which have unescaped contents.
33     *
34     * @var array<string,bool>
35     * @deprecated Use HTMLData::TAGS['rawText'] instead.
36     */
37    protected $rawTextElements = HTMLData::TAGS['rawText'];
38
39    /**
40     * The escape table for attribute values
41     *
42     * @var array<string,string>
43     */
44    protected $attributeEscapes = [
45        '&' => '&amp;',
46        "\xc2\xa0" => '&nbsp;',
47        '"' => '&quot;',
48    ];
49
50    /**
51     * The escape table for text nodes
52     *
53     * @var array<string,string>
54     */
55    protected $textEscapes = [
56        '&' => '&amp;',
57        "\xc2\xa0" => '&nbsp;',
58        '<' => '&lt;',
59        '>' => '&gt;',
60    ];
61
62    /**
63     * Attribute namespaces which have unqualified local names
64     *
65     * @var array<string,bool>
66     */
67    protected $unqualifiedNamespaces = [
68        HTMLData::NS_HTML => true,
69        HTMLData::NS_MATHML => true,
70        HTMLData::NS_SVG => true,
71    ];
72
73    protected bool $useSourceDoctype;
74    protected bool $reverseCoercion;
75    protected bool $scriptingFlag;
76
77    /**
78     * Constructor.
79     *
80     * @param array $options An associative array of options:
81     *   - scriptingFlag : Set this to false to disable scripting. True by default.
82     *   - useSourceDoctype : Emit the doctype used in the source. If this is
83     *     false or absent, an HTML doctype will be used.
84     *   - reverseCoercion : When formatting a DOM node, reverse the encoding
85     *     of invalid names. False by default.
86     */
87    public function __construct( $options = [] ) {
88        $options += [
89            'scriptingFlag' => true,
90            'useSourceDoctype' => false,
91            'reverseCoercion' => false,
92        ];
93        // Maintain compatibile values for this protected property, though
94        // it is deprecated.
95        if ( $options['scriptingFlag'] ) {
96            // @phan-suppress-next-line PhanDeprecatedProperty
97            $this->rawTextElements['noscript'] = true;
98        } else {
99            // @phan-suppress-next-line PhanDeprecatedProperty
100            unset( $this->rawTextElements['noscript'] );
101        }
102        $this->useSourceDoctype = $options['useSourceDoctype'];
103        $this->reverseCoercion = $options['reverseCoercion'];
104        $this->scriptingFlag = $options['scriptingFlag'];
105    }
106
107    protected function isRawTextElement( string $name ): bool {
108        if ( $name === 'noscript' ) {
109            // 'noscript' is a raw text element iff scriptingFlag is set
110            return $this->scriptingFlag;
111        }
112        return isset( HTMLData::TAGS['rawText'][$name] );
113    }
114
115    /** @inheritDoc */
116    public function startDocument( $fragmentNamespace, $fragmentName ) {
117        return "<!DOCTYPE html>";
118    }
119
120    /** @inheritDoc */
121    public function characters( SerializerNode $parent, $text, $start, $length ) {
122        $text = substr( $text, $start, $length );
123        if ( $parent->namespace !== HTMLData::NS_HTML
124            || !$this->isRawTextElement( $parent->name )
125        ) {
126            $text = strtr( $text, $this->textEscapes );
127        }
128        return $text;
129    }
130
131    /** @inheritDoc */
132    public function element( SerializerNode $parent, SerializerNode $node, $contents ) {
133        $name = $node->name;
134        $s = "<$name";
135        foreach ( $node->attrs->getValues() as $attrName => $attrValue ) {
136            $encValue = strtr( $attrValue, $this->attributeEscapes );
137            $s .= " $attrName=\"$encValue\"";
138        }
139        $s .= '>';
140        if ( $node->namespace === HTMLData::NS_HTML ) {
141            if ( isset( $contents[0] ) && $contents[0] === "\n"
142                && isset( HTMLData::TAGS['prefixLF'][$name] )
143            ) {
144                $s .= "\n$contents</$name>";
145            } elseif ( !isset( HTMLData::TAGS['void'][$name] ) ) {
146                $s .= "$contents</$name>";
147            }
148        } else {
149            $s .= "$contents</$name>";
150        }
151        return $s;
152    }
153
154    /** @inheritDoc */
155    public function comment( SerializerNode $parent, $text ) {
156        return "<!--$text-->";
157    }
158
159    /** @inheritDoc */
160    public function doctype( $name, $public, $system ) {
161        return '';
162    }
163
164    /**
165     * @param \DOMNode $node
166     * @return string
167     */
168    public function formatDOMNode( $node ) {
169        $contents = '';
170        if ( $node->firstChild ) {
171            foreach ( $node->childNodes as $child ) {
172                $contents .= $this->formatDOMNode( $child );
173            }
174        }
175
176        switch ( $node->nodeType ) {
177            case XML_ELEMENT_NODE:
178                '@phan-var \DOMElement $node'; /** @var \DOMElement $node */
179                return $this->formatDOMElement( $node, $contents );
180
181            case XML_DOCUMENT_NODE:
182                if ( !$this->useSourceDoctype ) {
183                    return "<!DOCTYPE html>" . $contents;
184                } else {
185                    return $contents;
186                }
187
188            case XML_DOCUMENT_FRAG_NODE:
189                return $contents;
190
191            case XML_TEXT_NODE:
192                '@phan-var \DOMCharacterData $node'; /** @var \DOMCharacterData $node */
193                $text = $node->data;
194                $parent = $node->parentNode;
195                if ( $parent->namespaceURI !== HTMLData::NS_HTML
196                    || !$this->isRawTextElement( $parent->nodeName )
197                ) {
198                    $text = strtr( $text, $this->textEscapes );
199                }
200                return $text;
201
202            case XML_CDATA_SECTION_NODE:
203                '@phan-var \DOMCdataSection $node'; /** @var \DOMCdataSection $node */
204                $parent = $node->parentNode;
205                if ( $parent->namespaceURI === HTMLData::NS_HTML ) {
206                    // CDATA is not allowed in HTML nodes
207                    return $node->data;
208                } else {
209                    return "<![CDATA[{$node->data}]]>";
210                }
211
212            case XML_PI_NODE:
213                '@phan-var \DOMProcessingInstruction $node'; /** @var \DOMProcessingInstruction $node */
214                return "<?{$node->target} {$node->data}>";
215
216            case XML_COMMENT_NODE:
217                '@phan-var \DOMComment $node'; /** @var \DOMComment $node */
218                return "<!--{$node->data}-->";
219
220            case XML_DOCUMENT_TYPE_NODE:
221                '@phan-var \DOMDocumentType $node'; /** @var \DOMDocumentType $node */
222                if ( $this->useSourceDoctype ) {
223                    return "<!DOCTYPE {$node->name}>";
224                } else {
225                    return '';
226                }
227
228            default:
229                return '';
230        }
231    }
232
233    /**
234     * @param \DOMElement $node
235     * @param string $contents
236     * @return string
237     */
238    public function formatDOMElement( $node, $contents ) {
239        $ns = $node->namespaceURI;
240        if ( $ns === null
241            || isset( $this->unqualifiedNamespaces[$ns] )
242            || !( $node->prefix )
243        ) {
244            $name = (string)$node->localName;
245        } else {
246            $name = $node->prefix . ':' . $node->localName;
247        }
248        if ( $this->reverseCoercion ) {
249            $name = DOMUtils::uncoerceName( $name );
250        }
251
252        $s = '<' . $name;
253        foreach ( $node->attributes as $attr ) {
254            switch ( $attr->namespaceURI ) {
255                case HTMLData::NS_XML:
256                    $attrName = 'xml:' . $attr->localName;
257                    break;
258                case HTMLData::NS_XMLNS:
259                    if ( $attr->localName === 'xmlns' ) {
260                        $attrName = 'xmlns';
261                    } else {
262                        $attrName = 'xmlns:' . $attr->localName;
263                    }
264                    break;
265                case HTMLData::NS_XLINK:
266                    $attrName = 'xlink:' . $attr->localName;
267                    break;
268                default:
269                    if ( strlen( $attr->prefix ) ) {
270                        $attrName = $attr->prefix . ':' . $attr->localName;
271                    } else {
272                        $attrName = $attr->localName;
273                    }
274            }
275            if ( $this->reverseCoercion ) {
276                $attrName = DOMUtils::uncoerceName( $attrName );
277            }
278            $encValue = strtr( $attr->value, $this->attributeEscapes );
279            $s .= " $attrName=\"$encValue\"";
280        }
281        $s .= '>';
282        if ( $ns === HTMLData::NS_HTML ) {
283            if ( isset( $contents[0] ) && $contents[0] === "\n"
284                && isset( HTMLData::TAGS['prefixLF'][$name] )
285            ) {
286                $s .= "\n$contents</$name>";
287            } elseif ( !isset( HTMLData::TAGS['void'][$name] ) ) {
288                $s .= "$contents</$name>";
289            }
290        } else {
291            $s .= "$contents</$name>";
292        }
293        return $s;
294    }
295}