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\UnexpectedValueException;
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
32 private $rootNodeName = 'response';
35 * Construct new XmlEncoder and allow to change the root node element name.
37 * @param string $rootNodeName
39 public function __construct($rootNodeName = 'response')
41 $this->rootNodeName = $rootNodeName;
47 public function encode($data, $format, array $context = array())
49 if ($data instanceof \DOMDocument) {
50 return $data->saveXML();
53 $xmlRootNodeName = $this->resolveXmlRootName($context);
55 $this->dom = $this->createDomDocument($context);
56 $this->format = $format;
57 $this->context = $context;
59 if (null !== $data && !is_scalar($data)) {
60 $root = $this->dom->createElement($xmlRootNodeName);
61 $this->dom->appendChild($root);
62 $this->buildXml($root, $data, $xmlRootNodeName);
64 $this->appendNode($this->dom, $data, $xmlRootNodeName);
67 return $this->dom->saveXML();
73 public function decode($data, $format, array $context = array())
75 if ('' === trim($data)) {
76 throw new UnexpectedValueException('Invalid XML data, it can not be empty.');
79 $internalErrors = libxml_use_internal_errors(true);
80 $disableEntities = libxml_disable_entity_loader(true);
81 libxml_clear_errors();
83 $dom = new \DOMDocument();
84 $dom->loadXML($data, LIBXML_NONET | LIBXML_NOBLANKS);
86 libxml_use_internal_errors($internalErrors);
87 libxml_disable_entity_loader($disableEntities);
89 if ($error = libxml_get_last_error()) {
90 libxml_clear_errors();
92 throw new UnexpectedValueException($error->message);
96 foreach ($dom->childNodes as $child) {
97 if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
98 throw new UnexpectedValueException('Document types are not allowed.');
100 if (!$rootNode && $child->nodeType !== XML_PI_NODE) {
105 // todo: throw an exception if the root node name is not correctly configured (bc)
107 if ($rootNode->hasChildNodes()) {
108 $xpath = new \DOMXPath($dom);
110 foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
111 $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
114 unset($data['@xmlns:xml']);
117 return $this->parseXml($rootNode);
120 return array_merge($data, (array) $this->parseXml($rootNode));
123 if (!$rootNode->hasAttributes()) {
124 return $rootNode->nodeValue;
129 foreach ($rootNode->attributes as $attrKey => $attr) {
130 $data['@'.$attrKey] = $attr->nodeValue;
133 $data['#'] = $rootNode->nodeValue;
141 public function supportsEncoding($format)
143 return 'xml' === $format;
149 public function supportsDecoding($format)
151 return 'xml' === $format;
155 * Sets the root node name.
157 * @param string $name root node name
159 public function setRootNodeName($name)
161 $this->rootNodeName = $name;
165 * Returns the root node name.
169 public function getRootNodeName()
171 return $this->rootNodeName;
175 * @param \DOMNode $node
180 final protected function appendXMLString(\DOMNode $node, $val)
182 if (strlen($val) > 0) {
183 $frag = $this->dom->createDocumentFragment();
184 $frag->appendXML($val);
185 $node->appendChild($frag);
194 * @param \DOMNode $node
199 final protected function appendText(\DOMNode $node, $val)
201 $nodeText = $this->dom->createTextNode($val);
202 $node->appendChild($nodeText);
208 * @param \DOMNode $node
213 final protected function appendCData(\DOMNode $node, $val)
215 $nodeText = $this->dom->createCDATASection($val);
216 $node->appendChild($nodeText);
222 * @param \DOMNode $node
223 * @param \DOMDocumentFragment $fragment
227 final protected function appendDocumentFragment(\DOMNode $node, $fragment)
229 if ($fragment instanceof \DOMDocumentFragment) {
230 $node->appendChild($fragment);
239 * Checks the name is a valid xml element name.
241 * @param string $name
245 final protected function isElementNameValid($name)
248 false === strpos($name, ' ') &&
249 preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
253 * Parse the input DOMNode into an array or a string.
255 * @param \DOMNode $node xml to parse
257 * @return array|string
259 private function parseXml(\DOMNode $node)
261 $data = $this->parseXmlAttributes($node);
263 $value = $this->parseXmlValue($node);
269 if (!is_array($value)) {
275 if (1 === count($value) && key($value)) {
276 $data[key($value)] = current($value);
281 foreach ($value as $key => $val) {
289 * Parse the input DOMNode attributes into an array.
291 * @param \DOMNode $node xml to parse
295 private function parseXmlAttributes(\DOMNode $node)
297 if (!$node->hasAttributes()) {
303 foreach ($node->attributes as $attr) {
304 if (!is_numeric($attr->nodeValue)) {
305 $data['@'.$attr->nodeName] = $attr->nodeValue;
310 if (false !== $val = filter_var($attr->nodeValue, FILTER_VALIDATE_INT)) {
311 $data['@'.$attr->nodeName] = $val;
316 $data['@'.$attr->nodeName] = (float) $attr->nodeValue;
323 * Parse the input DOMNode value (content and children) into an array or a string.
325 * @param \DOMNode $node xml to parse
327 * @return array|string
329 private function parseXmlValue(\DOMNode $node)
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 ($subnode->nodeType === XML_PI_NODE) {
346 $val = $this->parseXml($subnode);
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 UnexpectedValueException
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);
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 UnexpectedValueException(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 UnexpectedValueException
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.
514 * @param array $context
518 private function resolveXmlRootName(array $context = array())
520 return isset($context['xml_root_node_name'])
521 ? $context['xml_root_node_name']
522 : $this->rootNodeName;
526 * Create a DOM document, taking serializer options into account.
528 * @param array $context options that the encoder has access to
530 * @return \DOMDocument
532 private function createDomDocument(array $context)
534 $document = new \DOMDocument();
536 // Set an attribute on the DOM document specifying, as part of the XML declaration,
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',
547 foreach ($xmlOptions as $xmlOption => $documentProperty) {
548 if (isset($context[$xmlOption])) {
549 $document->$documentProperty = $context[$xmlOption];