Yaffs site version 1.1
[yaffs-website] / vendor / symfony / serializer / Encoder / XmlEncoder.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Serializer\Encoder;
13
14 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
15
16 /**
17  * Encodes XML data.
18  *
19  * @author Jordi Boggiano <j.boggiano@seld.be>
20  * @author John Wards <jwards@whiteoctober.co.uk>
21  * @author Fabian Vogler <fabian@equivalence.ch>
22  * @author Kévin Dunglas <dunglas@gmail.com>
23  */
24 class XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface
25 {
26     /**
27      * @var \DOMDocument
28      */
29     private $dom;
30     private $format;
31     private $context;
32     private $rootNodeName = 'response';
33
34     /**
35      * Construct new XmlEncoder and allow to change the root node element name.
36      *
37      * @param string $rootNodeName
38      */
39     public function __construct($rootNodeName = 'response')
40     {
41         $this->rootNodeName = $rootNodeName;
42     }
43
44     /**
45      * {@inheritdoc}
46      */
47     public function encode($data, $format, array $context = array())
48     {
49         if ($data instanceof \DOMDocument) {
50             return $data->saveXML();
51         }
52
53         $xmlRootNodeName = $this->resolveXmlRootName($context);
54
55         $this->dom = $this->createDomDocument($context);
56         $this->format = $format;
57         $this->context = $context;
58
59         if (null !== $data && !is_scalar($data)) {
60             $root = $this->dom->createElement($xmlRootNodeName);
61             $this->dom->appendChild($root);
62             $this->buildXml($root, $data, $xmlRootNodeName);
63         } else {
64             $this->appendNode($this->dom, $data, $xmlRootNodeName);
65         }
66
67         return $this->dom->saveXML();
68     }
69
70     /**
71      * {@inheritdoc}
72      */
73     public function decode($data, $format, array $context = array())
74     {
75         if ('' === trim($data)) {
76             throw new UnexpectedValueException('Invalid XML data, it can not be empty.');
77         }
78
79         $internalErrors = libxml_use_internal_errors(true);
80         $disableEntities = libxml_disable_entity_loader(true);
81         libxml_clear_errors();
82
83         $dom = new \DOMDocument();
84         $dom->loadXML($data, LIBXML_NONET | LIBXML_NOBLANKS);
85
86         libxml_use_internal_errors($internalErrors);
87         libxml_disable_entity_loader($disableEntities);
88
89         if ($error = libxml_get_last_error()) {
90             libxml_clear_errors();
91
92             throw new UnexpectedValueException($error->message);
93         }
94
95         $rootNode = null;
96         foreach ($dom->childNodes as $child) {
97             if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
98                 throw new UnexpectedValueException('Document types are not allowed.');
99             }
100             if (!$rootNode && $child->nodeType !== XML_PI_NODE) {
101                 $rootNode = $child;
102             }
103         }
104
105         // todo: throw an exception if the root node name is not correctly configured (bc)
106
107         if ($rootNode->hasChildNodes()) {
108             $xpath = new \DOMXPath($dom);
109             $data = array();
110             foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
111                 $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
112             }
113
114             unset($data['@xmlns:xml']);
115
116             if (empty($data)) {
117                 return $this->parseXml($rootNode);
118             }
119
120             return array_merge($data, (array) $this->parseXml($rootNode));
121         }
122
123         if (!$rootNode->hasAttributes()) {
124             return $rootNode->nodeValue;
125         }
126
127         $data = array();
128
129         foreach ($rootNode->attributes as $attrKey => $attr) {
130             $data['@'.$attrKey] = $attr->nodeValue;
131         }
132
133         $data['#'] = $rootNode->nodeValue;
134
135         return $data;
136     }
137
138     /**
139      * {@inheritdoc}
140      */
141     public function supportsEncoding($format)
142     {
143         return 'xml' === $format;
144     }
145
146     /**
147      * {@inheritdoc}
148      */
149     public function supportsDecoding($format)
150     {
151         return 'xml' === $format;
152     }
153
154     /**
155      * Sets the root node name.
156      *
157      * @param string $name root node name
158      */
159     public function setRootNodeName($name)
160     {
161         $this->rootNodeName = $name;
162     }
163
164     /**
165      * Returns the root node name.
166      *
167      * @return string
168      */
169     public function getRootNodeName()
170     {
171         return $this->rootNodeName;
172     }
173
174     /**
175      * @param \DOMNode $node
176      * @param string   $val
177      *
178      * @return bool
179      */
180     final protected function appendXMLString(\DOMNode $node, $val)
181     {
182         if (strlen($val) > 0) {
183             $frag = $this->dom->createDocumentFragment();
184             $frag->appendXML($val);
185             $node->appendChild($frag);
186
187             return true;
188         }
189
190         return false;
191     }
192
193     /**
194      * @param \DOMNode $node
195      * @param string   $val
196      *
197      * @return bool
198      */
199     final protected function appendText(\DOMNode $node, $val)
200     {
201         $nodeText = $this->dom->createTextNode($val);
202         $node->appendChild($nodeText);
203
204         return true;
205     }
206
207     /**
208      * @param \DOMNode $node
209      * @param string   $val
210      *
211      * @return bool
212      */
213     final protected function appendCData(\DOMNode $node, $val)
214     {
215         $nodeText = $this->dom->createCDATASection($val);
216         $node->appendChild($nodeText);
217
218         return true;
219     }
220
221     /**
222      * @param \DOMNode             $node
223      * @param \DOMDocumentFragment $fragment
224      *
225      * @return bool
226      */
227     final protected function appendDocumentFragment(\DOMNode $node, $fragment)
228     {
229         if ($fragment instanceof \DOMDocumentFragment) {
230             $node->appendChild($fragment);
231
232             return true;
233         }
234
235         return false;
236     }
237
238     /**
239      * Checks the name is a valid xml element name.
240      *
241      * @param string $name
242      *
243      * @return bool
244      */
245     final protected function isElementNameValid($name)
246     {
247         return $name &&
248             false === strpos($name, ' ') &&
249             preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
250     }
251
252     /**
253      * Parse the input DOMNode into an array or a string.
254      *
255      * @param \DOMNode $node xml to parse
256      *
257      * @return array|string
258      */
259     private function parseXml(\DOMNode $node)
260     {
261         $data = $this->parseXmlAttributes($node);
262
263         $value = $this->parseXmlValue($node);
264
265         if (!count($data)) {
266             return $value;
267         }
268
269         if (!is_array($value)) {
270             $data['#'] = $value;
271
272             return $data;
273         }
274
275         if (1 === count($value) && key($value)) {
276             $data[key($value)] = current($value);
277
278             return $data;
279         }
280
281         foreach ($value as $key => $val) {
282             $data[$key] = $val;
283         }
284
285         return $data;
286     }
287
288     /**
289      * Parse the input DOMNode attributes into an array.
290      *
291      * @param \DOMNode $node xml to parse
292      *
293      * @return array
294      */
295     private function parseXmlAttributes(\DOMNode $node)
296     {
297         if (!$node->hasAttributes()) {
298             return array();
299         }
300
301         $data = array();
302
303         foreach ($node->attributes as $attr) {
304             if (!is_numeric($attr->nodeValue)) {
305                 $data['@'.$attr->nodeName] = $attr->nodeValue;
306
307                 continue;
308             }
309
310             if (false !== $val = filter_var($attr->nodeValue, FILTER_VALIDATE_INT)) {
311                 $data['@'.$attr->nodeName] = $val;
312
313                 continue;
314             }
315
316             $data['@'.$attr->nodeName] = (float) $attr->nodeValue;
317         }
318
319         return $data;
320     }
321
322     /**
323      * Parse the input DOMNode value (content and children) into an array or a string.
324      *
325      * @param \DOMNode $node xml to parse
326      *
327      * @return array|string
328      */
329     private function parseXmlValue(\DOMNode $node)
330     {
331         if (!$node->hasChildNodes()) {
332             return $node->nodeValue;
333         }
334
335         if (1 === $node->childNodes->length && in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
336             return $node->firstChild->nodeValue;
337         }
338
339         $value = array();
340
341         foreach ($node->childNodes as $subnode) {
342             if ($subnode->nodeType === XML_PI_NODE) {
343                 continue;
344             }
345
346             $val = $this->parseXml($subnode);
347
348             if ('item' === $subnode->nodeName && isset($val['@key'])) {
349                 if (isset($val['#'])) {
350                     $value[$val['@key']] = $val['#'];
351                 } else {
352                     $value[$val['@key']] = $val;
353                 }
354             } else {
355                 $value[$subnode->nodeName][] = $val;
356             }
357         }
358
359         foreach ($value as $key => $val) {
360             if (is_array($val) && 1 === count($val)) {
361                 $value[$key] = current($val);
362             }
363         }
364
365         return $value;
366     }
367
368     /**
369      * Parse the data and convert it to DOMElements.
370      *
371      * @param \DOMNode     $parentNode
372      * @param array|object $data
373      * @param string|null  $xmlRootNodeName
374      *
375      * @return bool
376      *
377      * @throws UnexpectedValueException
378      */
379     private function buildXml(\DOMNode $parentNode, $data, $xmlRootNodeName = null)
380     {
381         $append = true;
382
383         if (is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
384             foreach ($data as $key => $data) {
385                 //Ah this is the magic @ attribute types.
386                 if (0 === strpos($key, '@') && $this->isElementNameValid($attributeName = substr($key, 1))) {
387                     if (!is_scalar($data)) {
388                         $data = $this->serializer->normalize($data, $this->format, $this->context);
389                     }
390                     $parentNode->setAttribute($attributeName, $data);
391                 } elseif ($key === '#') {
392                     $append = $this->selectNodeType($parentNode, $data);
393                 } elseif (is_array($data) && false === is_numeric($key)) {
394                     // Is this array fully numeric keys?
395                     if (ctype_digit(implode('', array_keys($data)))) {
396                         /*
397                          * Create nodes to append to $parentNode based on the $key of this array
398                          * Produces <xml><item>0</item><item>1</item></xml>
399                          * From array("item" => array(0,1));.
400                          */
401                         foreach ($data as $subData) {
402                             $append = $this->appendNode($parentNode, $subData, $key);
403                         }
404                     } else {
405                         $append = $this->appendNode($parentNode, $data, $key);
406                     }
407                 } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
408                     $append = $this->appendNode($parentNode, $data, 'item', $key);
409                 } else {
410                     $append = $this->appendNode($parentNode, $data, $key);
411                 }
412             }
413
414             return $append;
415         }
416
417         if (is_object($data)) {
418             $data = $this->serializer->normalize($data, $this->format, $this->context);
419             if (null !== $data && !is_scalar($data)) {
420                 return $this->buildXml($parentNode, $data, $xmlRootNodeName);
421             }
422
423             // top level data object was normalized into a scalar
424             if (!$parentNode->parentNode->parentNode) {
425                 $root = $parentNode->parentNode;
426                 $root->removeChild($parentNode);
427
428                 return $this->appendNode($root, $data, $xmlRootNodeName);
429             }
430
431             return $this->appendNode($parentNode, $data, 'data');
432         }
433
434         throw new UnexpectedValueException(sprintf('An unexpected value could not be serialized: %s', var_export($data, true)));
435     }
436
437     /**
438      * Selects the type of node to create and appends it to the parent.
439      *
440      * @param \DOMNode     $parentNode
441      * @param array|object $data
442      * @param string       $nodeName
443      * @param string       $key
444      *
445      * @return bool
446      */
447     private function appendNode(\DOMNode $parentNode, $data, $nodeName, $key = null)
448     {
449         $node = $this->dom->createElement($nodeName);
450         if (null !== $key) {
451             $node->setAttribute('key', $key);
452         }
453         $appendNode = $this->selectNodeType($node, $data);
454         // we may have decided not to append this node, either in error or if its $nodeName is not valid
455         if ($appendNode) {
456             $parentNode->appendChild($node);
457         }
458
459         return $appendNode;
460     }
461
462     /**
463      * Checks if a value contains any characters which would require CDATA wrapping.
464      *
465      * @param string $val
466      *
467      * @return bool
468      */
469     private function needsCdataWrapping($val)
470     {
471         return 0 < preg_match('/[<>&]/', $val);
472     }
473
474     /**
475      * Tests the value being passed and decide what sort of element to create.
476      *
477      * @param \DOMNode $node
478      * @param mixed    $val
479      *
480      * @return bool
481      *
482      * @throws UnexpectedValueException
483      */
484     private function selectNodeType(\DOMNode $node, $val)
485     {
486         if (is_array($val)) {
487             return $this->buildXml($node, $val);
488         } elseif ($val instanceof \SimpleXMLElement) {
489             $child = $this->dom->importNode(dom_import_simplexml($val), true);
490             $node->appendChild($child);
491         } elseif ($val instanceof \Traversable) {
492             $this->buildXml($node, $val);
493         } elseif (is_object($val)) {
494             return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
495         } elseif (is_numeric($val)) {
496             return $this->appendText($node, (string) $val);
497         } elseif (is_string($val) && $this->needsCdataWrapping($val)) {
498             return $this->appendCData($node, $val);
499         } elseif (is_string($val)) {
500             return $this->appendText($node, $val);
501         } elseif (is_bool($val)) {
502             return $this->appendText($node, (int) $val);
503         } elseif ($val instanceof \DOMNode) {
504             $child = $this->dom->importNode($val, true);
505             $node->appendChild($child);
506         }
507
508         return true;
509     }
510
511     /**
512      * Get real XML root node name, taking serializer options into account.
513      *
514      * @param array $context
515      *
516      * @return string
517      */
518     private function resolveXmlRootName(array $context = array())
519     {
520         return isset($context['xml_root_node_name'])
521             ? $context['xml_root_node_name']
522             : $this->rootNodeName;
523     }
524
525     /**
526      * Create a DOM document, taking serializer options into account.
527      *
528      * @param array $context options that the encoder has access to
529      *
530      * @return \DOMDocument
531      */
532     private function createDomDocument(array $context)
533     {
534         $document = new \DOMDocument();
535
536         // Set an attribute on the DOM document specifying, as part of the XML declaration,
537         $xmlOptions = array(
538             // nicely formats output with indentation and extra space
539             'xml_format_output' => 'formatOutput',
540             // the version number of the document
541             'xml_version' => 'xmlVersion',
542             // the encoding of the document
543             'xml_encoding' => 'encoding',
544             // whether the document is standalone
545             'xml_standalone' => 'xmlStandalone',
546         );
547         foreach ($xmlOptions as $xmlOption => $documentProperty) {
548             if (isset($context[$xmlOption])) {
549                 $document->$documentProperty = $context[$xmlOption];
550             }
551         }
552
553         return $document;
554     }
555 }