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';
36 * Construct new XmlEncoder and allow to change the root node element name.
38 * @param string $rootNodeName
39 * @param int|null $loadOptions A bit field of LIBXML_* constants
41 public function __construct($rootNodeName = 'response', $loadOptions = null)
43 $this->rootNodeName = $rootNodeName;
44 $this->loadOptions = null !== $loadOptions ? $loadOptions : LIBXML_NONET | LIBXML_NOBLANKS;
50 public function encode($data, $format, array $context = array())
52 if ($data instanceof \DOMDocument) {
53 return $data->saveXML();
56 $xmlRootNodeName = $this->resolveXmlRootName($context);
58 $this->dom = $this->createDomDocument($context);
59 $this->format = $format;
60 $this->context = $context;
62 if (null !== $data && !is_scalar($data)) {
63 $root = $this->dom->createElement($xmlRootNodeName);
64 $this->dom->appendChild($root);
65 $this->buildXml($root, $data, $xmlRootNodeName);
67 $this->appendNode($this->dom, $data, $xmlRootNodeName);
70 return $this->dom->saveXML();
76 public function decode($data, $format, array $context = array())
78 if ('' === trim($data)) {
79 throw new UnexpectedValueException('Invalid XML data, it can not be empty.');
82 $internalErrors = libxml_use_internal_errors(true);
83 $disableEntities = libxml_disable_entity_loader(true);
84 libxml_clear_errors();
86 $dom = new \DOMDocument();
87 $dom->loadXML($data, $this->loadOptions);
89 libxml_use_internal_errors($internalErrors);
90 libxml_disable_entity_loader($disableEntities);
92 if ($error = libxml_get_last_error()) {
93 libxml_clear_errors();
95 throw new UnexpectedValueException($error->message);
99 foreach ($dom->childNodes as $child) {
100 if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
101 throw new UnexpectedValueException('Document types are not allowed.');
103 if (!$rootNode && $child->nodeType !== XML_PI_NODE) {
108 // todo: throw an exception if the root node name is not correctly configured (bc)
110 if ($rootNode->hasChildNodes()) {
111 $xpath = new \DOMXPath($dom);
113 foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
114 $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
117 unset($data['@xmlns:xml']);
120 return $this->parseXml($rootNode);
123 return array_merge($data, (array) $this->parseXml($rootNode));
126 if (!$rootNode->hasAttributes()) {
127 return $rootNode->nodeValue;
132 foreach ($rootNode->attributes as $attrKey => $attr) {
133 $data['@'.$attrKey] = $attr->nodeValue;
136 $data['#'] = $rootNode->nodeValue;
144 public function supportsEncoding($format)
146 return 'xml' === $format;
152 public function supportsDecoding($format)
154 return 'xml' === $format;
158 * Sets the root node name.
160 * @param string $name root node name
162 public function setRootNodeName($name)
164 $this->rootNodeName = $name;
168 * Returns the root node name.
172 public function getRootNodeName()
174 return $this->rootNodeName;
178 * @param \DOMNode $node
183 final protected function appendXMLString(\DOMNode $node, $val)
185 if (strlen($val) > 0) {
186 $frag = $this->dom->createDocumentFragment();
187 $frag->appendXML($val);
188 $node->appendChild($frag);
197 * @param \DOMNode $node
202 final protected function appendText(\DOMNode $node, $val)
204 $nodeText = $this->dom->createTextNode($val);
205 $node->appendChild($nodeText);
211 * @param \DOMNode $node
216 final protected function appendCData(\DOMNode $node, $val)
218 $nodeText = $this->dom->createCDATASection($val);
219 $node->appendChild($nodeText);
225 * @param \DOMNode $node
226 * @param \DOMDocumentFragment $fragment
230 final protected function appendDocumentFragment(\DOMNode $node, $fragment)
232 if ($fragment instanceof \DOMDocumentFragment) {
233 $node->appendChild($fragment);
242 * Checks the name is a valid xml element name.
244 * @param string $name
248 final protected function isElementNameValid($name)
251 false === strpos($name, ' ') &&
252 preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
256 * Parse the input DOMNode into an array or a string.
258 * @param \DOMNode $node xml to parse
260 * @return array|string
262 private function parseXml(\DOMNode $node)
264 $data = $this->parseXmlAttributes($node);
266 $value = $this->parseXmlValue($node);
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.
294 * @param \DOMNode $node xml to parse
298 private function parseXmlAttributes(\DOMNode $node)
300 if (!$node->hasAttributes()) {
306 foreach ($node->attributes as $attr) {
307 if (!is_numeric($attr->nodeValue)) {
308 $data['@'.$attr->nodeName] = $attr->nodeValue;
313 if (false !== $val = filter_var($attr->nodeValue, FILTER_VALIDATE_INT)) {
314 $data['@'.$attr->nodeName] = $val;
319 $data['@'.$attr->nodeName] = (float) $attr->nodeValue;
326 * Parse the input DOMNode value (content and children) into an array or a string.
328 * @param \DOMNode $node xml to parse
330 * @return array|string
332 private function parseXmlValue(\DOMNode $node)
334 if (!$node->hasChildNodes()) {
335 return $node->nodeValue;
338 if (1 === $node->childNodes->length && in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
339 return $node->firstChild->nodeValue;
344 foreach ($node->childNodes as $subnode) {
345 if ($subnode->nodeType === XML_PI_NODE) {
349 $val = $this->parseXml($subnode);
351 if ('item' === $subnode->nodeName && isset($val['@key'])) {
352 if (isset($val['#'])) {
353 $value[$val['@key']] = $val['#'];
355 $value[$val['@key']] = $val;
358 $value[$subnode->nodeName][] = $val;
362 foreach ($value as $key => $val) {
363 if (is_array($val) && 1 === count($val)) {
364 $value[$key] = current($val);
372 * Parse the data and convert it to DOMElements.
374 * @param \DOMNode $parentNode
375 * @param array|object $data
376 * @param string|null $xmlRootNodeName
380 * @throws UnexpectedValueException
382 private function buildXml(\DOMNode $parentNode, $data, $xmlRootNodeName = null)
386 if (is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
387 foreach ($data as $key => $data) {
388 //Ah this is the magic @ attribute types.
389 if (0 === strpos($key, '@') && $this->isElementNameValid($attributeName = substr($key, 1))) {
390 if (!is_scalar($data)) {
391 $data = $this->serializer->normalize($data, $this->format, $this->context);
393 $parentNode->setAttribute($attributeName, $data);
394 } elseif ($key === '#') {
395 $append = $this->selectNodeType($parentNode, $data);
396 } elseif (is_array($data) && false === is_numeric($key)) {
397 // Is this array fully numeric keys?
398 if (ctype_digit(implode('', array_keys($data)))) {
400 * Create nodes to append to $parentNode based on the $key of this array
401 * Produces <xml><item>0</item><item>1</item></xml>
402 * From array("item" => array(0,1));.
404 foreach ($data as $subData) {
405 $append = $this->appendNode($parentNode, $subData, $key);
408 $append = $this->appendNode($parentNode, $data, $key);
410 } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
411 $append = $this->appendNode($parentNode, $data, 'item', $key);
413 $append = $this->appendNode($parentNode, $data, $key);
420 if (is_object($data)) {
421 $data = $this->serializer->normalize($data, $this->format, $this->context);
422 if (null !== $data && !is_scalar($data)) {
423 return $this->buildXml($parentNode, $data, $xmlRootNodeName);
426 // top level data object was normalized into a scalar
427 if (!$parentNode->parentNode->parentNode) {
428 $root = $parentNode->parentNode;
429 $root->removeChild($parentNode);
431 return $this->appendNode($root, $data, $xmlRootNodeName);
434 return $this->appendNode($parentNode, $data, 'data');
437 throw new UnexpectedValueException(sprintf('An unexpected value could not be serialized: %s', var_export($data, true)));
441 * Selects the type of node to create and appends it to the parent.
443 * @param \DOMNode $parentNode
444 * @param array|object $data
445 * @param string $nodeName
450 private function appendNode(\DOMNode $parentNode, $data, $nodeName, $key = null)
452 $node = $this->dom->createElement($nodeName);
454 $node->setAttribute('key', $key);
456 $appendNode = $this->selectNodeType($node, $data);
457 // we may have decided not to append this node, either in error or if its $nodeName is not valid
459 $parentNode->appendChild($node);
466 * Checks if a value contains any characters which would require CDATA wrapping.
472 private function needsCdataWrapping($val)
474 return 0 < preg_match('/[<>&]/', $val);
478 * Tests the value being passed and decide what sort of element to create.
480 * @param \DOMNode $node
485 * @throws UnexpectedValueException
487 private function selectNodeType(\DOMNode $node, $val)
489 if (is_array($val)) {
490 return $this->buildXml($node, $val);
491 } elseif ($val instanceof \SimpleXMLElement) {
492 $child = $this->dom->importNode(dom_import_simplexml($val), true);
493 $node->appendChild($child);
494 } elseif ($val instanceof \Traversable) {
495 $this->buildXml($node, $val);
496 } elseif (is_object($val)) {
497 return $this->selectNodeType($node, $this->serializer->normalize($val, $this->format, $this->context));
498 } elseif (is_numeric($val)) {
499 return $this->appendText($node, (string) $val);
500 } elseif (is_string($val) && $this->needsCdataWrapping($val)) {
501 return $this->appendCData($node, $val);
502 } elseif (is_string($val)) {
503 return $this->appendText($node, $val);
504 } elseif (is_bool($val)) {
505 return $this->appendText($node, (int) $val);
506 } elseif ($val instanceof \DOMNode) {
507 $child = $this->dom->importNode($val, true);
508 $node->appendChild($child);
515 * Get real XML root node name, taking serializer options into account.
517 * @param array $context
521 private function resolveXmlRootName(array $context = array())
523 return isset($context['xml_root_node_name'])
524 ? $context['xml_root_node_name']
525 : $this->rootNodeName;
529 * Create a DOM document, taking serializer options into account.
531 * @param array $context options that the encoder has access to
533 * @return \DOMDocument
535 private function createDomDocument(array $context)
537 $document = new \DOMDocument();
539 // Set an attribute on the DOM document specifying, as part of the XML declaration,
541 // nicely formats output with indentation and extra space
542 'xml_format_output' => 'formatOutput',
543 // the version number of the document
544 'xml_version' => 'xmlVersion',
545 // the encoding of the document
546 'xml_encoding' => 'encoding',
547 // whether the document is standalone
548 'xml_standalone' => 'xmlStandalone',
550 foreach ($xmlOptions as $xmlOption => $documentProperty) {
551 if (isset($context[$xmlOption])) {
552 $document->$documentProperty = $context[$xmlOption];