PluginProbe
WindPress – Tailwind CSS integration for WordPress / 3.2.86
WindPress – Tailwind CSS integration for WordPress v3.2.86
3.2.89 3.2.88 3.2.87 3.2.86 3.2.85 3.2.84 3.2.83 3.2.82 3.2.81 trunk 3.0.0 3.0.1 3.0.10 3.0.11 3.0.12 3.0.13 3.0.14 3.0.15 3.0.16 3.0.17 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 All 143 releases
windpress / vendor / masterminds / html5 / src / HTML5 / Serializer / OutputRules.php

OutputRules.php in WindPress – Tailwind CSS integration for WordPress 3.2.86, at vendor/masterminds/html5/src/HTML5/Serializer/OutputRules.php

393 lines 14.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * @file
5 * The rules for generating output in the serializer.
6 *
7 * These output rules are likely to generate output similar to the document that
8 * was parsed. It is not intended to output exactly the document that was parsed.
9 */
10 namespace WindPressDeps\Masterminds\HTML5\Serializer;
11
12 use WindPressDeps\Masterminds\HTML5\Elements;
13 /**
14 * Generate the output html5 based on element rules.
15 */
16 class OutputRules implements RulesInterface
17 {
18 /**
19 * Defined in http://www.w3.org/TR/html51/infrastructure.html#html-namespace-0.
20 */
21 const NAMESPACE_HTML = 'http://www.w3.org/1999/xhtml';
22 const NAMESPACE_MATHML = 'http://www.w3.org/1998/Math/MathML';
23 const NAMESPACE_SVG = 'http://www.w3.org/2000/svg';
24 const NAMESPACE_XLINK = 'http://www.w3.org/1999/xlink';
25 const NAMESPACE_XML = 'http://www.w3.org/XML/1998/namespace';
26 const NAMESPACE_XMLNS = 'http://www.w3.org/2000/xmlns/';
27 /**
28 * Holds the HTML5 element names that causes a namespace switch.
29 *
30 * @var array
31 */
32 protected $implicitNamespaces = array(self::NAMESPACE_HTML, self::NAMESPACE_SVG, self::NAMESPACE_MATHML, self::NAMESPACE_XML, self::NAMESPACE_XMLNS);
33 const IM_IN_HTML = 1;
34 const IM_IN_SVG = 2;
35 const IM_IN_MATHML = 3;
36 /**
37 * Used as cache to detect if is available ENT_HTML5.
38 *
39 * @var bool
40 */
41 private $hasHTML5 = \false;
42 protected $traverser;
43 protected $encode = \false;
44 protected $out;
45 protected $outputMode;
46 private $xpath;
47 protected $nonBooleanAttributes = array(
48 /*
49 array(
50 'nodeNamespace'=>'http://www.w3.org/1999/xhtml',
51 'attrNamespace'=>'http://www.w3.org/1999/xhtml',
52
53 'nodeName'=>'img', 'nodeName'=>array('img', 'a'),
54 'attrName'=>'alt', 'attrName'=>array('title', 'alt'),
55 ),
56 */
57 array('nodeNamespace' => 'http://www.w3.org/1999/xhtml', 'attrName' => array('href', 'hreflang', 'http-equiv', 'icon', 'id', 'keytype', 'kind', 'label', 'lang', 'language', 'list', 'maxlength', 'media', 'method', 'name', 'placeholder', 'rel', 'rows', 'rowspan', 'sandbox', 'spellcheck', 'scope', 'seamless', 'shape', 'size', 'sizes', 'span', 'src', 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', 'summary', 'tabindex', 'target', 'title', 'type', 'value', 'width', 'border', 'charset', 'cite', 'class', 'code', 'codebase', 'color', 'cols', 'colspan', 'content', 'coords', 'data', 'datetime', 'default', 'dir', 'dirname', 'enctype', 'for', 'form', 'formaction', 'headers', 'height', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'bgcolor')),
58 array('nodeNamespace' => 'http://www.w3.org/1999/xhtml', 'xpath' => 'starts-with(local-name(), \'data-\')'),
59 );
60 const DOCTYPE = '<!DOCTYPE html>';
61 public function __construct($output, $options = array())
62 {
63 if (isset($options['encode_entities'])) {
64 $this->encode = $options['encode_entities'];
65 }
66 $this->outputMode = static::IM_IN_HTML;
67 $this->out = $output;
68 $this->hasHTML5 = defined('ENT_HTML5');
69 }
70 public function addRule(array $rule)
71 {
72 $this->nonBooleanAttributes[] = $rule;
73 }
74 public function setTraverser(Traverser $traverser)
75 {
76 $this->traverser = $traverser;
77 return $this;
78 }
79 public function unsetTraverser()
80 {
81 $this->traverser = null;
82 return $this;
83 }
84 public function document($dom)
85 {
86 $this->doctype();
87 if ($dom->documentElement) {
88 foreach ($dom->childNodes as $node) {
89 $this->traverser->node($node);
90 }
91 $this->nl();
92 }
93 }
94 protected function doctype()
95 {
96 $this->wr(static::DOCTYPE);
97 $this->nl();
98 }
99 /**
100 * @param \DOMElement $ele
101 */
102 public function element($ele)
103 {
104 $name = $ele->tagName;
105 // Per spec:
106 // If the element has a declared namespace in the HTML, MathML or
107 // SVG namespaces, we use the lname instead of the tagName.
108 if ($this->traverser->isLocalElement($ele)) {
109 $name = $ele->localName;
110 }
111 // If we are in SVG or MathML there is special handling.
112 // Using if/elseif instead of switch because it's faster in PHP.
113 if ('svg' == $name) {
114 $this->outputMode = static::IM_IN_SVG;
115 $name = Elements::normalizeSvgElement($name);
116 } elseif ('math' == $name) {
117 $this->outputMode = static::IM_IN_MATHML;
118 }
119 $this->openTag($ele);
120 // The tag is already self-closed (`<svg />` or `<math />`) in `openTag` if there are no child nodes.
121 $handledAsVoidTag = $this->outputMode !== static::IM_IN_HTML && !$ele->hasChildNodes();
122 if (Elements::isA($name, Elements::TEXT_RAW)) {
123 foreach ($ele->childNodes as $child) {
124 if ($child instanceof \DOMCharacterData) {
125 $this->wr($child->data);
126 } elseif ($child instanceof \DOMElement) {
127 $this->element($child);
128 }
129 }
130 } else {
131 // Handle children.
132 if ($ele->hasChildNodes()) {
133 $this->traverser->children($ele->childNodes);
134 }
135 // Close out the SVG or MathML special handling.
136 if ('svg' == $name || 'math' == $name) {
137 $this->outputMode = static::IM_IN_HTML;
138 }
139 }
140 // If not unary, add a closing tag.
141 if (!$handledAsVoidTag && !Elements::isA($name, Elements::VOID_TAG)) {
142 $this->closeTag($ele);
143 }
144 }
145 /**
146 * Write a text node.
147 *
148 * @param \DOMText $ele The text node to write.
149 */
150 public function text($ele)
151 {
152 if (isset($ele->parentNode) && isset($ele->parentNode->tagName) && Elements::isA($ele->parentNode->localName, Elements::TEXT_RAW)) {
153 $this->wr($ele->data);
154 return;
155 }
156 // FIXME: This probably needs some flags set.
157 $this->wr($this->enc($ele->data));
158 }
159 public function cdata($ele)
160 {
161 // This encodes CDATA.
162 $this->wr($ele->ownerDocument->saveXML($ele));
163 }
164 public function comment($ele)
165 {
166 // These produce identical output.
167 // $this->wr('<!--')->wr($ele->data)->wr('-->');
168 $this->wr($ele->ownerDocument->saveXML($ele));
169 }
170 public function processorInstruction($ele)
171 {
172 $this->wr('<?')->wr($ele->target)->wr(' ')->wr($ele->data)->wr('?>');
173 }
174 /**
175 * Write the namespace attributes.
176 *
177 * @param \DOMNode $ele The element being written.
178 */
179 protected function namespaceAttrs($ele)
180 {
181 if (!$this->xpath || $this->xpath->document !== $ele->ownerDocument) {
182 $this->xpath = new \DOMXPath($ele->ownerDocument);
183 }
184 foreach ($this->xpath->query('namespace::*[not(.=../../namespace::*)]', $ele) as $nsNode) {
185 if (!in_array($nsNode->nodeValue, $this->implicitNamespaces)) {
186 $this->wr(' ')->wr($nsNode->nodeName)->wr('="')->wr($nsNode->nodeValue)->wr('"');
187 }
188 }
189 }
190 /**
191 * Write the opening tag.
192 *
193 * Tags for HTML, MathML, and SVG are in the local name. Otherwise, use the
194 * qualified name (8.3).
195 *
196 * @param \DOMNode $ele The element being written.
197 */
198 protected function openTag($ele)
199 {
200 $this->wr('<')->wr($this->traverser->isLocalElement($ele) ? $ele->localName : $ele->tagName);
201 $this->attrs($ele);
202 $this->namespaceAttrs($ele);
203 if ($this->outputMode == static::IM_IN_HTML) {
204 $this->wr('>');
205 } else if ($ele->hasChildNodes()) {
206 $this->wr('>');
207 } else {
208 $this->wr(' />');
209 }
210 }
211 protected function attrs($ele)
212 {
213 // FIXME: Needs support for xml, xmlns, xlink, and namespaced elements.
214 if (!$ele->hasAttributes()) {
215 return $this;
216 }
217 // TODO: Currently, this always writes name="value", and does not do
218 // value-less attributes.
219 $map = $ele->attributes;
220 $len = $map->length;
221 for ($i = 0; $i < $len; ++$i) {
222 $node = $map->item($i);
223 $val = $this->enc($node->value, \true);
224 // XXX: The spec says that we need to ensure that anything in
225 // the XML, XMLNS, or XLink NS's should use the canonical
226 // prefix. It seems that DOM does this for us already, but there
227 // may be exceptions.
228 $name = $node->nodeName;
229 // Special handling for attributes in SVG and MathML.
230 // Using if/elseif instead of switch because it's faster in PHP.
231 if ($this->outputMode == static::IM_IN_SVG) {
232 $name = Elements::normalizeSvgAttribute($name);
233 } elseif ($this->outputMode == static::IM_IN_MATHML) {
234 $name = Elements::normalizeMathMlAttribute($name);
235 }
236 $this->wr(' ')->wr($name);
237 if (isset($val) && '' !== $val || $this->nonBooleanAttribute($node)) {
238 $this->wr('="')->wr($val)->wr('"');
239 }
240 }
241 }
242 protected function nonBooleanAttribute(\DOMAttr $attr)
243 {
244 $ele = $attr->ownerElement;
245 foreach ($this->nonBooleanAttributes as $rule) {
246 if (isset($rule['nodeNamespace']) && $rule['nodeNamespace'] !== $ele->namespaceURI) {
247 continue;
248 }
249 if (isset($rule['attNamespace']) && $rule['attNamespace'] !== $attr->namespaceURI) {
250 continue;
251 }
252 if (isset($rule['nodeName']) && !is_array($rule['nodeName']) && $rule['nodeName'] !== $ele->localName) {
253 continue;
254 }
255 if (isset($rule['nodeName']) && is_array($rule['nodeName']) && !in_array($ele->localName, $rule['nodeName'], \true)) {
256 continue;
257 }
258 if (isset($rule['attrName']) && !is_array($rule['attrName']) && $rule['attrName'] !== $attr->localName) {
259 continue;
260 }
261 if (isset($rule['attrName']) && is_array($rule['attrName']) && !in_array($attr->localName, $rule['attrName'], \true)) {
262 continue;
263 }
264 if (isset($rule['xpath'])) {
265 $xp = $this->getXPath($attr);
266 if (isset($rule['prefixes'])) {
267 foreach ($rule['prefixes'] as $nsPrefix => $ns) {
268 $xp->registerNamespace($nsPrefix, $ns);
269 }
270 }
271 if (!$xp->evaluate($rule['xpath'], $attr)) {
272 continue;
273 }
274 }
275 return \true;
276 }
277 return \false;
278 }
279 private function getXPath(\DOMNode $node)
280 {
281 if (!$this->xpath) {
282 $this->xpath = new \DOMXPath($node->ownerDocument);
283 }
284 return $this->xpath;
285 }
286 /**
287 * Write the closing tag.
288 *
289 * Tags for HTML, MathML, and SVG are in the local name. Otherwise, use the
290 * qualified name (8.3).
291 *
292 * @param \DOMNode $ele The element being written.
293 */
294 protected function closeTag($ele)
295 {
296 if ($this->outputMode == static::IM_IN_HTML || $ele->hasChildNodes()) {
297 $this->wr('</')->wr($this->traverser->isLocalElement($ele) ? $ele->localName : $ele->tagName)->wr('>');
298 }
299 }
300 /**
301 * Write to the output.
302 *
303 * @param string $text The string to put into the output
304 *
305 * @return $this
306 */
307 protected function wr($text)
308 {
309 fwrite($this->out, $text);
310 return $this;
311 }
312 /**
313 * Write a new line character.
314 *
315 * @return $this
316 */
317 protected function nl()
318 {
319 fwrite($this->out, \PHP_EOL);
320 return $this;
321 }
322 /**
323 * Encode text.
324 *
325 * When encode is set to false, the default value, the text passed in is
326 * escaped per section 8.3 of the html5 spec. For details on how text is
327 * escaped see the escape() method.
328 *
329 * When encoding is set to true the text is converted to named character
330 * references where appropriate. Section 8.1.4 Character references of the
331 * html5 spec refers to using named character references. This is useful for
332 * characters that can't otherwise legally be used in the text.
333 *
334 * The named character references are listed in section 8.5.
335 *
336 * @see http://www.w3.org/TR/2013/CR-html5-20130806/syntax.html#named-character-references True encoding will turn all named character references into their entities.
337 * This includes such characters as +.# and many other common ones. By default
338 * encoding here will just escape &'<>".
339 *
340 * Note, PHP 5.4+ has better html5 encoding.
341 *
342 * @todo Use the Entities class in php 5.3 to have html5 entities.
343 *
344 * @param string $text Text to encode.
345 * @param bool $attribute True if we are encoding an attrubute, false otherwise.
346 *
347 * @return string The encoded text.
348 */
349 protected function enc($text, $attribute = \false)
350 {
351 // Escape the text rather than convert to named character references.
352 if (!$this->encode) {
353 return $this->escape($text, $attribute);
354 }
355 // If we are in PHP 5.4+ we can use the native html5 entity functionality to
356 // convert the named character references.
357 if ($this->hasHTML5) {
358 return htmlentities($text, \ENT_HTML5 | \ENT_SUBSTITUTE | \ENT_QUOTES, 'UTF-8', \false);
359 } else {
360 return strtr($text, HTML5Entities::$map);
361 }
362 }
363 /**
364 * Escape test.
365 *
366 * According to the html5 spec section 8.3 Serializing HTML fragments, text
367 * within tags that are not style, script, xmp, iframe, noembed, and noframes
368 * need to be properly escaped.
369 *
370 * The & should be converted to &amp;, no breaking space unicode characters
371 * converted to &nbsp;, when in attribute mode the " should be converted to
372 * &quot;, and when not in attribute mode the < and > should be converted to
373 * &lt; and &gt;.
374 *
375 * @see http://www.w3.org/TR/2013/CR-html5-20130806/syntax.html#escapingString
376 *
377 * @param string $text Text to escape.
378 * @param bool $attribute True if we are escaping an attrubute, false otherwise.
379 */
380 protected function escape($text, $attribute = \false)
381 {
382 // Not using htmlspecialchars because, while it does escaping, it doesn't
383 // match the requirements of section 8.5. For example, it doesn't handle
384 // non-breaking spaces.
385 if ($attribute) {
386 $replace = array('"' => '&quot;', '&' => '&amp;', " " => '&nbsp;');
387 } else {
388 $replace = array('<' => '&lt;', '>' => '&gt;', '&' => '&amp;', " " => '&nbsp;');
389 }
390 return strtr($text, $replace);
391 }
392 }
393