40f61167b36989e1f2a630cb86f931b85f25a9de
[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 (ctype_digit($attr->nodeValue)) {
305                 $data['@'.$attr->nodeName] = (int) $attr->nodeValue;
306             } else {
307                 $data['@'.$attr->nodeName] = $attr->nodeValue;
308             }
309         }
310
311         return $data;
312     }
313
314     /**
315      * Parse the input DOMNode value (content and children) into an array or a string.
316      *
317      * @param \DOMNode $node xml to parse
318      *
319      * @return array|string
320      */
321     private function parseXmlValue(\DOMNode $node)
322     {
323         if (!$node->hasChildNodes()) {
324             return $node->nodeValue;
325         }
326
327         if (1 === $node->childNodes->length && in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
328             return $node->firstChild->nodeValue;
329         }
330
331         $value = array();
332
333         foreach ($node->childNodes as $subnode) {
334             if ($subnode->nodeType === XML_PI_NODE) {
335                 continue;
336             }
337
338             $val = $this->parseXml($subnode);
339
340             if ('item' === $subnode->nodeName && isset($val['@key'])) {
341                 if (isset($val['#'])) {
342                     $value[$val['@key']] = $val['#'];
343                 } else {
344                     $value[$val['@key']] = $val;
345                 }
346             } else {
347                 $value[$subnode->nodeName][] = $val;
348             }
349         }
350
351         foreach ($value as $key => $val) {
352             if (is_array($val) && 1 === count($val)) {
353                 $value[$key] = current($val);
354             }
355         }
356
357         return $value;
358     }
359
360     /**
361      * Parse the data and convert it to DOMElements.
362      *
363      * @param \DOMNode     $parentNode
364      * @param array|object $data
365      * @param string|null  $xmlRootNodeName
366      *
367      * @return bool
368      *
369      * @throws UnexpectedValueException
370      */
371     private function buildXml(\DOMNode $parentNode, $data, $xmlRootNodeName = null)
372     {
373         $append = true;
374
375         if (is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
376             foreach ($data as $key => $data) {
377                 //Ah this is the magic @ attribute types.
378                 if (0 === strpos($key, '@') && $this->isElementNameValid($attributeName = substr($key, 1))) {
379                     if (!is_scalar($data)) {
380                         $data = $this->serializer->normalize($data, $this->format, $this->context);
381                     }
382                     $parentNode->setAttribute($attributeName, $data);
383                 } elseif ($key === '#') {
384                     $append = $this->selectNodeType($parentNode, $data);
385                 } elseif (is_array($data) && false === is_numeric($key)) {
386                     // Is this array fully numeric keys?
387                     if (ctype_digit(implode('', array_keys($data)))) {
388                         /*
389                          * Create nodes to append to $parentNode based on the $key of this array
390                          * Produces <xml><item>0</item><item>1</item></xml>
391                          * From array("item" => array(0,1));.
392                          */
393                         foreach ($data as $subData) {
394                             $append = $this->appendNode($parentNode, $subData, $key);
395                         }
396                     } else {
397                         $append = $this->appendNode($parentNode, $data, $key);
398                     }
399                 } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
400                     $append = $this->appendNode($parentNode, $data, 'item', $key);
401                 } else {
402                     $append = $this->appendNode($parentNode, $data, $key);
403                 }
404             }
405
406             return $append;
407         }
408
409         if (is_object($data)) {
410             $data = $this->serializer->normalize($data, $this->format, $this->context);
411             if (null !== $data && !is_scalar($data)) {
412                 return $this->buildXml($parentNode, $data, $xmlRootNodeName);
413             }
414
415             // top level data object was normalized into a scalar
416             if (!$parentNode->parentNode->parentNode) {
417                 $root = $parentNode->parentNode;
418                 $root->removeChild($parentNode);
419
420                 return $this->appendNode($root, $data, $xmlRootNodeName);
421             }
422
423             return $this->appendNode($parentNode, $data, 'data');
424         }
425
426         throw new UnexpectedValueException(sprintf('An unexpected value could not be serialized: %s', var_export($data, true)));
427     }
428
429     /**
430      * Selects the type of node to create and appends it to the parent.
431      *
432      * @param \DOMNode     $parentNode
433      * @param array|object $data
434      * @param string       $nodeName
435      * @param string       $key
436      *
437      * @return bool
438      */
439     private function appendNode(\DOMNode $parentNode, $data, $nodeName, $key = null)
440     {
441         $node = $this->dom->createElement($nodeName);
442         if (null !== $key) {
443             $node->setAttribute('key', $key);
444         }
445         $appendNode = $this->selectNodeType($node, $data);
446         // we may have decided not to append this node, either in error or if its $nodeName is not valid
447         if ($appendNode) {
448             $parentNode->appendChild($node);
449         }
450
451         return $appendNode;
452     }
453
454     /**
455      * Checks if a value contains any characters which would require CDATA wrapping.
456      *
457      * @param string $val
458      *
459      * @return bool
460      */
461     private function needsCdataWrapping($val)
462     {
463         return preg_match('/[<>&]/', $val);
464     }
465
466     /**
467      * Tests the value being passed and decide what sort of element to create.
468      *
469      * @param \DOMNode $node
470      * @param mixed    $val
471      *
472      * @return bool
473      *
474      * @throws UnexpectedValueException
475      */
476     private function selectNodeType(\DOMNode $node, $val)
477     {
478         if (is_array($val)) {
479             return $this->buildXml($node, $val);
480         } elseif ($val instanceof \SimpleXMLElement) {
481             $child = $this->dom->importNode(dom_import_simplexml($val), true);
482             $node->appendChild($child);
483         } elseif ($val instanceof \Traversable) {
484             $this->buildXml($node, $val);
485         } elseif (is_object($val)) {
486             return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
487         } elseif (is_numeric($val)) {
488             return $this->appendText($node, (string) $val);
489         } elseif (is_string($val) && $this->needsCdataWrapping($val)) {
490             return $this->appendCData($node, $val);
491         } elseif (is_string($val)) {
492             return $this->appendText($node, $val);
493         } elseif (is_bool($val)) {
494             return $this->appendText($node, (int) $val);
495         } elseif ($val instanceof \DOMNode) {
496             $child = $this->dom->importNode($val, true);
497             $node->appendChild($child);
498         }
499
500         return true;
501     }
502
503     /**
504      * Get real XML root node name, taking serializer options into account.
505      *
506      * @param array $context
507      *
508      * @return string
509      */
510     private function resolveXmlRootName(array $context = array())
511     {
512         return isset($context['xml_root_node_name'])
513             ? $context['xml_root_node_name']
514             : $this->rootNodeName;
515     }
516
517     /**
518      * Create a DOM document, taking serializer options into account.
519      *
520      * @param array $context options that the encoder has access to
521      *
522      * @return \DOMDocument
523      */
524     private function createDomDocument(array $context)
525     {
526         $document = new \DOMDocument();
527
528         // Set an attribute on the DOM document specifying, as part of the XML declaration,
529         $xmlOptions = array(
530             // nicely formats output with indentation and extra space
531             'xml_format_output' => 'formatOutput',
532             // the version number of the document
533             'xml_version' => 'xmlVersion',
534             // the encoding of the document
535             'xml_encoding' => 'encoding',
536             // whether the document is standalone
537             'xml_standalone' => 'xmlStandalone',
538         );
539         foreach ($xmlOptions as $xmlOption => $documentProperty) {
540             if (isset($context[$xmlOption])) {
541                 $document->$documentProperty = $context[$xmlOption];
542             }
543         }
544
545         return $document;
546     }
547 }