Added the Search API Synonym module to deal specifically with licence and license...
[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\NotEncodableValueException;
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     const FORMAT = 'xml';
27
28     /**
29      * @var \DOMDocument
30      */
31     private $dom;
32     private $format;
33     private $context;
34     private $rootNodeName = 'response';
35     private $loadOptions;
36
37     /**
38      * Construct new XmlEncoder and allow to change the root node element name.
39      *
40      * @param string   $rootNodeName
41      * @param int|null $loadOptions  A bit field of LIBXML_* constants
42      */
43     public function __construct($rootNodeName = 'response', $loadOptions = null)
44     {
45         $this->rootNodeName = $rootNodeName;
46         $this->loadOptions = null !== $loadOptions ? $loadOptions : LIBXML_NONET | LIBXML_NOBLANKS;
47     }
48
49     /**
50      * {@inheritdoc}
51      */
52     public function encode($data, $format, array $context = array())
53     {
54         if ($data instanceof \DOMDocument) {
55             return $data->saveXML();
56         }
57
58         $xmlRootNodeName = $this->resolveXmlRootName($context);
59
60         $this->dom = $this->createDomDocument($context);
61         $this->format = $format;
62         $this->context = $context;
63
64         if (null !== $data && !is_scalar($data)) {
65             $root = $this->dom->createElement($xmlRootNodeName);
66             $this->dom->appendChild($root);
67             $this->buildXml($root, $data, $xmlRootNodeName);
68         } else {
69             $this->appendNode($this->dom, $data, $xmlRootNodeName);
70         }
71
72         return $this->dom->saveXML();
73     }
74
75     /**
76      * {@inheritdoc}
77      */
78     public function decode($data, $format, array $context = array())
79     {
80         if ('' === trim($data)) {
81             throw new NotEncodableValueException('Invalid XML data, it can not be empty.');
82         }
83
84         $internalErrors = libxml_use_internal_errors(true);
85         $disableEntities = libxml_disable_entity_loader(true);
86         libxml_clear_errors();
87
88         $dom = new \DOMDocument();
89         $dom->loadXML($data, $this->loadOptions);
90
91         libxml_use_internal_errors($internalErrors);
92         libxml_disable_entity_loader($disableEntities);
93
94         if ($error = libxml_get_last_error()) {
95             libxml_clear_errors();
96
97             throw new NotEncodableValueException($error->message);
98         }
99
100         $rootNode = null;
101         foreach ($dom->childNodes as $child) {
102             if (XML_DOCUMENT_TYPE_NODE === $child->nodeType) {
103                 throw new NotEncodableValueException('Document types are not allowed.');
104             }
105             if (!$rootNode && XML_PI_NODE !== $child->nodeType) {
106                 $rootNode = $child;
107             }
108         }
109
110         // todo: throw an exception if the root node name is not correctly configured (bc)
111
112         if ($rootNode->hasChildNodes()) {
113             $xpath = new \DOMXPath($dom);
114             $data = array();
115             foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
116                 $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
117             }
118
119             unset($data['@xmlns:xml']);
120
121             if (empty($data)) {
122                 return $this->parseXml($rootNode, $context);
123             }
124
125             return array_merge($data, (array) $this->parseXml($rootNode, $context));
126         }
127
128         if (!$rootNode->hasAttributes()) {
129             return $rootNode->nodeValue;
130         }
131
132         $data = array();
133
134         foreach ($rootNode->attributes as $attrKey => $attr) {
135             $data['@'.$attrKey] = $attr->nodeValue;
136         }
137
138         $data['#'] = $rootNode->nodeValue;
139
140         return $data;
141     }
142
143     /**
144      * {@inheritdoc}
145      */
146     public function supportsEncoding($format)
147     {
148         return self::FORMAT === $format;
149     }
150
151     /**
152      * {@inheritdoc}
153      */
154     public function supportsDecoding($format)
155     {
156         return self::FORMAT === $format;
157     }
158
159     /**
160      * Sets the root node name.
161      *
162      * @param string $name Root node name
163      */
164     public function setRootNodeName($name)
165     {
166         $this->rootNodeName = $name;
167     }
168
169     /**
170      * Returns the root node name.
171      *
172      * @return string
173      */
174     public function getRootNodeName()
175     {
176         return $this->rootNodeName;
177     }
178
179     /**
180      * @param \DOMNode $node
181      * @param string   $val
182      *
183      * @return bool
184      */
185     final protected function appendXMLString(\DOMNode $node, $val)
186     {
187         if (\strlen($val) > 0) {
188             $frag = $this->dom->createDocumentFragment();
189             $frag->appendXML($val);
190             $node->appendChild($frag);
191
192             return true;
193         }
194
195         return false;
196     }
197
198     /**
199      * @param \DOMNode $node
200      * @param string   $val
201      *
202      * @return bool
203      */
204     final protected function appendText(\DOMNode $node, $val)
205     {
206         $nodeText = $this->dom->createTextNode($val);
207         $node->appendChild($nodeText);
208
209         return true;
210     }
211
212     /**
213      * @param \DOMNode $node
214      * @param string   $val
215      *
216      * @return bool
217      */
218     final protected function appendCData(\DOMNode $node, $val)
219     {
220         $nodeText = $this->dom->createCDATASection($val);
221         $node->appendChild($nodeText);
222
223         return true;
224     }
225
226     /**
227      * @param \DOMNode             $node
228      * @param \DOMDocumentFragment $fragment
229      *
230      * @return bool
231      */
232     final protected function appendDocumentFragment(\DOMNode $node, $fragment)
233     {
234         if ($fragment instanceof \DOMDocumentFragment) {
235             $node->appendChild($fragment);
236
237             return true;
238         }
239
240         return false;
241     }
242
243     /**
244      * Checks the name is a valid xml element name.
245      *
246      * @param string $name
247      *
248      * @return bool
249      */
250     final protected function isElementNameValid($name)
251     {
252         return $name &&
253             false === strpos($name, ' ') &&
254             preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
255     }
256
257     /**
258      * Parse the input DOMNode into an array or a string.
259      *
260      * @return array|string
261      */
262     private function parseXml(\DOMNode $node, array $context = array())
263     {
264         $data = $this->parseXmlAttributes($node, $context);
265
266         $value = $this->parseXmlValue($node, $context);
267
268         if (!\count($data)) {
269             return $value;
270         }
271
272         if (!\is_array($value)) {
273             $data['#'] = $value;
274
275             return $data;
276         }
277
278         if (1 === \count($value) && key($value)) {
279             $data[key($value)] = current($value);
280
281             return $data;
282         }
283
284         foreach ($value as $key => $val) {
285             $data[$key] = $val;
286         }
287
288         return $data;
289     }
290
291     /**
292      * Parse the input DOMNode attributes into an array.
293      *
294      * @return array
295      */
296     private function parseXmlAttributes(\DOMNode $node, array $context = array())
297     {
298         if (!$node->hasAttributes()) {
299             return array();
300         }
301
302         $data = array();
303         $typeCastAttributes = $this->resolveXmlTypeCastAttributes($context);
304
305         foreach ($node->attributes as $attr) {
306             if (!is_numeric($attr->nodeValue) || !$typeCastAttributes) {
307                 $data['@'.$attr->nodeName] = $attr->nodeValue;
308
309                 continue;
310             }
311
312             if (false !== $val = filter_var($attr->nodeValue, FILTER_VALIDATE_INT)) {
313                 $data['@'.$attr->nodeName] = $val;
314
315                 continue;
316             }
317
318             $data['@'.$attr->nodeName] = (float) $attr->nodeValue;
319         }
320
321         return $data;
322     }
323
324     /**
325      * Parse the input DOMNode value (content and children) into an array or a string.
326      *
327      * @return array|string
328      */
329     private function parseXmlValue(\DOMNode $node, array $context = array())
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 (XML_PI_NODE === $subnode->nodeType) {
343                 continue;
344             }
345
346             $val = $this->parseXml($subnode, $context);
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 NotEncodableValueException
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                 } elseif (null !== $data || !isset($this->context['remove_empty_tags']) || false === $this->context['remove_empty_tags']) {
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 NotEncodableValueException(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 NotEncodableValueException
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      * @return string
515      */
516     private function resolveXmlRootName(array $context = array())
517     {
518         return isset($context['xml_root_node_name'])
519             ? $context['xml_root_node_name']
520             : $this->rootNodeName;
521     }
522
523     /**
524      * Get XML option for type casting attributes Defaults to true.
525      *
526      * @param array $context
527      *
528      * @return bool
529      */
530     private function resolveXmlTypeCastAttributes(array $context = array())
531     {
532         return isset($context['xml_type_cast_attributes'])
533             ? (bool) $context['xml_type_cast_attributes']
534             : true;
535     }
536
537     /**
538      * Create a DOM document, taking serializer options into account.
539      *
540      * @param array $context Options that the encoder has access to
541      *
542      * @return \DOMDocument
543      */
544     private function createDomDocument(array $context)
545     {
546         $document = new \DOMDocument();
547
548         // Set an attribute on the DOM document specifying, as part of the XML declaration,
549         $xmlOptions = array(
550             // nicely formats output with indentation and extra space
551             'xml_format_output' => 'formatOutput',
552             // the version number of the document
553             'xml_version' => 'xmlVersion',
554             // the encoding of the document
555             'xml_encoding' => 'encoding',
556             // whether the document is standalone
557             'xml_standalone' => 'xmlStandalone',
558         );
559         foreach ($xmlOptions as $xmlOption => $documentProperty) {
560             if (isset($context[$xmlOption])) {
561                 $document->$documentProperty = $context[$xmlOption];
562             }
563         }
564
565         return $document;
566     }
567 }