2 namespace Masterminds\HTML5\Serializer;
5 * Traverser for walking a DOM tree.
7 * This is a concrete traverser designed to convert a DOM tree into an
8 * HTML5 document. It is not intended to be a generic DOMTreeWalker
11 * @see http://www.w3.org/TR/2012/CR-html5-20121217/syntax.html#serializing-html-fragments
17 * Namespaces that should be treated as "local" to HTML5.
19 static $local_ns = array(
20 'http://www.w3.org/1999/xhtml' => 'html',
21 'http://www.w3.org/1998/Math/MathML' => 'math',
22 'http://www.w3.org/2000/svg' => 'svg'
29 protected $encode = false;
38 * @param DOMNode|DOMNodeList $dom
39 * The document or node to traverse.
40 * @param resource $out
41 * A stream that allows writing. The traverser will output into this
43 * @param array $options
44 * An array or options for the traverser as key/value pairs. These include:
45 * - encode_entities: A bool to specify if full encding should happen for all named
46 * charachter references. Defaults to false which escapes &'<>".
47 * - output_rules: The path to the class handling the output rules.
49 public function __construct($dom, $out, RulesInterface $rules, $options = array())
53 $this->rules = $rules;
54 $this->options = $options;
56 $this->rules->setTraverser($this);
60 * Tell the traverser to walk the DOM.
62 * @return resource $out
63 * Returns the output stream.
65 public function walk()
67 if ($this->dom instanceof \DOMDocument) {
68 $this->rules->document($this->dom);
69 } elseif ($this->dom instanceof \DOMDocumentFragment) {
70 // Document fragments are a special case. Only the children need to
72 if ($this->dom->hasChildNodes()) {
73 $this->children($this->dom->childNodes);
75 } // If NodeList, loop
76 elseif ($this->dom instanceof \DOMNodeList) {
77 // If this is a NodeList of DOMDocuments this will not work.
78 $this->children($this->dom);
79 } // Else assume this is a DOMNode-like datastructure.
81 $this->node($this->dom);
88 * Process a node in the DOM.
91 * A node implementing \DOMNode.
93 public function node($node)
95 // A listing of types is at http://php.net/manual/en/dom.constants.php
96 switch ($node->nodeType) {
97 case XML_ELEMENT_NODE:
98 $this->rules->element($node);
101 $this->rules->text($node);
103 case XML_CDATA_SECTION_NODE:
104 $this->rules->cdata($node);
107 $this->rules->processorInstruction($node);
109 case XML_COMMENT_NODE:
110 $this->rules->comment($node);
112 // Currently we don't support embedding DTDs.
114 //print '<!-- Skipped -->';
120 * Walk through all the nodes on a node list.
122 * @param \DOMNodeList $nl
123 * A list of child elements to walk through.
125 public function children($nl)
127 foreach ($nl as $node) {
133 * Is an element local?
136 * An element that implement \DOMNode.
138 * @return bool True if local and false otherwise.
140 public function isLocalElement($ele)
142 $uri = $ele->namespaceURI;
147 return isset(static::$local_ns[$uri]);