4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Encoder;
14 use Symfony\Component\Serializer\Exception\NotEncodableValueException;
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>
24 class XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface
34 private $rootNodeName = 'response';
38 * Construct new XmlEncoder and allow to change the root node element name.
40 * @param string $rootNodeName
41 * @param int|null $loadOptions A bit field of LIBXML_* constants
43 public function __construct($rootNodeName = 'response', $loadOptions = null)
45 $this->rootNodeName = $rootNodeName;
46 $this->loadOptions = null !== $loadOptions ? $loadOptions : LIBXML_NONET | LIBXML_NOBLANKS;
52 public function encode($data, $format, array $context = array())
54 if ($data instanceof \DOMDocument) {
55 return $data->saveXML();
58 $xmlRootNodeName = $this->resolveXmlRootName($context);
60 $this->dom = $this->createDomDocument($context);
61 $this->format = $format;
62 $this->context = $context;
64 if (null !== $data && !is_scalar($data)) {
65 $root = $this->dom->createElement($xmlRootNodeName);
66 $this->dom->appendChild($root);
67 $this->buildXml($root, $data, $xmlRootNodeName);
69 $this->appendNode($this->dom, $data, $xmlRootNodeName);
72 return $this->dom->saveXML();
78 public function decode($data, $format, array $context = array())
80 if ('' === trim($data)) {
81 throw new NotEncodableValueException('Invalid XML data, it can not be empty.');
84 $internalErrors = libxml_use_internal_errors(true);
85 $disableEntities = libxml_disable_entity_loader(true);
86 libxml_clear_errors();
88 $dom = new \DOMDocument();
89 $dom->loadXML($data, $this->loadOptions);
91 libxml_use_internal_errors($internalErrors);
92 libxml_disable_entity_loader($disableEntities);
94 if ($error = libxml_get_last_error()) {
95 libxml_clear_errors();
97 throw new NotEncodableValueException($error->message);
101 foreach ($dom->childNodes as $child) {
102 if (XML_DOCUMENT_TYPE_NODE === $child->nodeType) {
103 throw new NotEncodableValueException('Document types are not allowed.');
105 if (!$rootNode && XML_PI_NODE !== $child->nodeType) {
110 // todo: throw an exception if the root node name is not correctly configured (bc)
112 if ($rootNode->hasChildNodes()) {
113 $xpath = new \DOMXPath($dom);
115 foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
116 $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
119 unset($data['@xmlns:xml']);
122 return $this->parseXml($rootNode, $context);
125 return array_merge($data, (array) $this->parseXml($rootNode, $context));
128 if (!$rootNode->hasAttributes()) {
129 return $rootNode->nodeValue;
134 foreach ($rootNode->attributes as $attrKey => $attr) {
135 $data['@'.$attrKey] = $attr->nodeValue;
138 $data['#'] = $rootNode->nodeValue;
146 public function supportsEncoding($format)
148 return self::FORMAT === $format;
154 public function supportsDecoding($format)
156 return self::FORMAT === $format;
160 * Sets the root node name.
162 * @param string $name Root node name
164 public function setRootNodeName($name)
166 $this->rootNodeName = $name;
170 * Returns the root node name.
174 public function getRootNodeName()
176 return $this->rootNodeName;
180 * @param \DOMNode $node
185 final protected function appendXMLString(\DOMNode $node, $val)
187 if (\strlen($val) > 0) {
188 $frag = $this->dom->createDocumentFragment();
189 $frag->appendXML($val);
190 $node->appendChild($frag);
199 * @param \DOMNode $node
204 final protected function appendText(\DOMNode $node, $val)
206 $nodeText = $this->dom->createTextNode($val);
207 $node->appendChild($nodeText);
213 * @param \DOMNode $node
218 final protected function appendCData(\DOMNode $node, $val)
220 $nodeText = $this->dom->createCDATASection($val);
221 $node->appendChild($nodeText);
227 * @param \DOMNode $node
228 * @param \DOMDocumentFragment $fragment
232 final protected function appendDocumentFragment(\DOMNode $node, $fragment)
234 if ($fragment instanceof \DOMDocumentFragment) {
235 $node->appendChild($fragment);
244 * Checks the name is a valid xml element name.
246 * @param string $name
250 final protected function isElementNameValid($name)
253 false === strpos($name, ' ') &&
254 preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
258 * Parse the input DOMNode into an array or a string.
260 * @return array|string
262 private function parseXml(\DOMNode $node, array $context = array())
264 $data = $this->parseXmlAttributes($node, $context);
266 $value = $this->parseXmlValue($node, $context);
268 if (!\count($data)) {
272 if (!\is_array($value)) {
278 if (1 === \count($value) && key($value)) {
279 $data[key($value)] = current($value);
284 foreach ($value as $key => $val) {
292 * Parse the input DOMNode attributes into an array.
296 private function parseXmlAttributes(\DOMNode $node, array $context = array())
298 if (!$node->hasAttributes()) {
303 $typeCastAttributes = $this->resolveXmlTypeCastAttributes($context);
305 foreach ($node->attributes as $attr) {
306 if (!is_numeric($attr->nodeValue) || !$typeCastAttributes) {
307 $data['@'.$attr->nodeName] = $attr->nodeValue;
312 if (false !== $val = filter_var($attr->nodeValue, FILTER_VALIDATE_INT)) {
313 $data['@'.$attr->nodeName] = $val;
318 $data['@'.$attr->nodeName] = (float) $attr->nodeValue;
325 * Parse the input DOMNode value (content and children) into an array or a string.
327 * @return array|string
329 private function parseXmlValue(\DOMNode $node, array $context = array())
331 if (!$node->hasChildNodes()) {
332 return $node->nodeValue;
335 if (1 === $node->childNodes->length && \in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
336 return $node->firstChild->nodeValue;
341 foreach ($node->childNodes as $subnode) {
342 if (XML_PI_NODE === $subnode->nodeType) {
346 $val = $this->parseXml($subnode, $context);
348 if ('item' === $subnode->nodeName && isset($val['@key'])) {
349 if (isset($val['#'])) {
350 $value[$val['@key']] = $val['#'];
352 $value[$val['@key']] = $val;
355 $value[$subnode->nodeName][] = $val;
359 foreach ($value as $key => $val) {
360 if (\is_array($val) && 1 === \count($val)) {
361 $value[$key] = current($val);
369 * Parse the data and convert it to DOMElements.
371 * @param \DOMNode $parentNode
372 * @param array|object $data
373 * @param string|null $xmlRootNodeName
377 * @throws NotEncodableValueException
379 private function buildXml(\DOMNode $parentNode, $data, $xmlRootNodeName = null)
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);
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)))) {
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));.
401 foreach ($data as $subData) {
402 $append = $this->appendNode($parentNode, $subData, $key);
405 $append = $this->appendNode($parentNode, $data, $key);
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);
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);
423 // top level data object was normalized into a scalar
424 if (!$parentNode->parentNode->parentNode) {
425 $root = $parentNode->parentNode;
426 $root->removeChild($parentNode);
428 return $this->appendNode($root, $data, $xmlRootNodeName);
431 return $this->appendNode($parentNode, $data, 'data');
434 throw new NotEncodableValueException(sprintf('An unexpected value could not be serialized: %s', var_export($data, true)));
438 * Selects the type of node to create and appends it to the parent.
440 * @param \DOMNode $parentNode
441 * @param array|object $data
442 * @param string $nodeName
447 private function appendNode(\DOMNode $parentNode, $data, $nodeName, $key = null)
449 $node = $this->dom->createElement($nodeName);
451 $node->setAttribute('key', $key);
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
456 $parentNode->appendChild($node);
463 * Checks if a value contains any characters which would require CDATA wrapping.
469 private function needsCdataWrapping($val)
471 return 0 < preg_match('/[<>&]/', $val);
475 * Tests the value being passed and decide what sort of element to create.
477 * @param \DOMNode $node
482 * @throws NotEncodableValueException
484 private function selectNodeType(\DOMNode $node, $val)
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);
512 * Get real XML root node name, taking serializer options into account.
516 private function resolveXmlRootName(array $context = array())
518 return isset($context['xml_root_node_name'])
519 ? $context['xml_root_node_name']
520 : $this->rootNodeName;
524 * Get XML option for type casting attributes Defaults to true.
526 * @param array $context
530 private function resolveXmlTypeCastAttributes(array $context = array())
532 return isset($context['xml_type_cast_attributes'])
533 ? (bool) $context['xml_type_cast_attributes']
538 * Create a DOM document, taking serializer options into account.
540 * @param array $context Options that the encoder has access to
542 * @return \DOMDocument
544 private function createDomDocument(array $context)
546 $document = new \DOMDocument();
548 // Set an attribute on the DOM document specifying, as part of the XML declaration,
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',
559 foreach ($xmlOptions as $xmlOption => $documentProperty) {
560 if (isset($context[$xmlOption])) {
561 $document->$documentProperty = $context[$xmlOption];