XmlEncoder.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Encoder;
  11. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  12. /**
  13. * Encodes XML data.
  14. *
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. * @author John Wards <jwards@whiteoctober.co.uk>
  17. * @author Fabian Vogler <fabian@equivalence.ch>
  18. * @author Kévin Dunglas <dunglas@gmail.com>
  19. */
  20. class XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface
  21. {
  22. /**
  23. * @var \DOMDocument
  24. */
  25. private $dom;
  26. private $format;
  27. private $context;
  28. private $rootNodeName = 'response';
  29. private $loadOptions;
  30. /**
  31. * Construct new XmlEncoder and allow to change the root node element name.
  32. *
  33. * @param string $rootNodeName
  34. * @param int|null $loadOptions A bit field of LIBXML_* constants
  35. */
  36. public function __construct($rootNodeName = 'response', $loadOptions = null)
  37. {
  38. $this->rootNodeName = $rootNodeName;
  39. $this->loadOptions = null !== $loadOptions ? $loadOptions : LIBXML_NONET | LIBXML_NOBLANKS;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function encode($data, $format, array $context = array())
  45. {
  46. if ($data instanceof \DOMDocument) {
  47. return $data->saveXML();
  48. }
  49. $xmlRootNodeName = $this->resolveXmlRootName($context);
  50. $this->dom = $this->createDomDocument($context);
  51. $this->format = $format;
  52. $this->context = $context;
  53. if (null !== $data && !is_scalar($data)) {
  54. $root = $this->dom->createElement($xmlRootNodeName);
  55. $this->dom->appendChild($root);
  56. $this->buildXml($root, $data, $xmlRootNodeName);
  57. } else {
  58. $this->appendNode($this->dom, $data, $xmlRootNodeName);
  59. }
  60. return $this->dom->saveXML();
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function decode($data, $format, array $context = array())
  66. {
  67. if ('' === trim($data)) {
  68. throw new UnexpectedValueException('Invalid XML data, it can not be empty.');
  69. }
  70. $internalErrors = libxml_use_internal_errors(true);
  71. $disableEntities = libxml_disable_entity_loader(true);
  72. libxml_clear_errors();
  73. $dom = new \DOMDocument();
  74. $dom->loadXML($data, $this->loadOptions);
  75. libxml_use_internal_errors($internalErrors);
  76. libxml_disable_entity_loader($disableEntities);
  77. if ($error = libxml_get_last_error()) {
  78. libxml_clear_errors();
  79. throw new UnexpectedValueException($error->message);
  80. }
  81. foreach ($dom->childNodes as $child) {
  82. if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
  83. throw new UnexpectedValueException('Document types are not allowed.');
  84. }
  85. }
  86. $rootNode = $dom->firstChild;
  87. // todo: throw an exception if the root node name is not correctly configured (bc)
  88. if ($rootNode->hasChildNodes()) {
  89. $xpath = new \DOMXPath($dom);
  90. $data = array();
  91. foreach ($xpath->query('namespace::*', $dom->documentElement) as $nsNode) {
  92. $data['@'.$nsNode->nodeName] = $nsNode->nodeValue;
  93. }
  94. unset($data['@xmlns:xml']);
  95. if (empty($data)) {
  96. return $this->parseXml($rootNode);
  97. }
  98. return array_merge($data, (array) $this->parseXml($rootNode));
  99. }
  100. if (!$rootNode->hasAttributes()) {
  101. return $rootNode->nodeValue;
  102. }
  103. $data = array();
  104. foreach ($rootNode->attributes as $attrKey => $attr) {
  105. $data['@'.$attrKey] = $attr->nodeValue;
  106. }
  107. $data['#'] = $rootNode->nodeValue;
  108. return $data;
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public function supportsEncoding($format)
  114. {
  115. return 'xml' === $format;
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function supportsDecoding($format)
  121. {
  122. return 'xml' === $format;
  123. }
  124. /**
  125. * Sets the root node name.
  126. *
  127. * @param string $name root node name
  128. */
  129. public function setRootNodeName($name)
  130. {
  131. $this->rootNodeName = $name;
  132. }
  133. /**
  134. * Returns the root node name.
  135. *
  136. * @return string
  137. */
  138. public function getRootNodeName()
  139. {
  140. return $this->rootNodeName;
  141. }
  142. /**
  143. * @param \DOMNode $node
  144. * @param string $val
  145. *
  146. * @return bool
  147. */
  148. final protected function appendXMLString(\DOMNode $node, $val)
  149. {
  150. if (strlen($val) > 0) {
  151. $frag = $this->dom->createDocumentFragment();
  152. $frag->appendXML($val);
  153. $node->appendChild($frag);
  154. return true;
  155. }
  156. return false;
  157. }
  158. /**
  159. * @param \DOMNode $node
  160. * @param string $val
  161. *
  162. * @return bool
  163. */
  164. final protected function appendText(\DOMNode $node, $val)
  165. {
  166. $nodeText = $this->dom->createTextNode($val);
  167. $node->appendChild($nodeText);
  168. return true;
  169. }
  170. /**
  171. * @param \DOMNode $node
  172. * @param string $val
  173. *
  174. * @return bool
  175. */
  176. final protected function appendCData(\DOMNode $node, $val)
  177. {
  178. $nodeText = $this->dom->createCDATASection($val);
  179. $node->appendChild($nodeText);
  180. return true;
  181. }
  182. /**
  183. * @param \DOMNode $node
  184. * @param \DOMDocumentFragment $fragment
  185. *
  186. * @return bool
  187. */
  188. final protected function appendDocumentFragment(\DOMNode $node, $fragment)
  189. {
  190. if ($fragment instanceof \DOMDocumentFragment) {
  191. $node->appendChild($fragment);
  192. return true;
  193. }
  194. return false;
  195. }
  196. /**
  197. * Checks the name is a valid xml element name.
  198. *
  199. * @param string $name
  200. *
  201. * @return bool
  202. */
  203. final protected function isElementNameValid($name)
  204. {
  205. return $name &&
  206. false === strpos($name, ' ') &&
  207. preg_match('#^[\pL_][\pL0-9._:-]*$#ui', $name);
  208. }
  209. /**
  210. * Parse the input DOMNode into an array or a string.
  211. *
  212. * @param \DOMNode $node xml to parse
  213. *
  214. * @return array|string
  215. */
  216. private function parseXml(\DOMNode $node)
  217. {
  218. $data = $this->parseXmlAttributes($node);
  219. $value = $this->parseXmlValue($node);
  220. if (!count($data)) {
  221. return $value;
  222. }
  223. if (!is_array($value)) {
  224. $data['#'] = $value;
  225. return $data;
  226. }
  227. if (1 === count($value) && key($value)) {
  228. $data[key($value)] = current($value);
  229. return $data;
  230. }
  231. foreach ($value as $key => $val) {
  232. $data[$key] = $val;
  233. }
  234. return $data;
  235. }
  236. /**
  237. * Parse the input DOMNode attributes into an array.
  238. *
  239. * @param \DOMNode $node xml to parse
  240. *
  241. * @return array
  242. */
  243. private function parseXmlAttributes(\DOMNode $node)
  244. {
  245. if (!$node->hasAttributes()) {
  246. return array();
  247. }
  248. $data = array();
  249. foreach ($node->attributes as $attr) {
  250. if (ctype_digit($attr->nodeValue)) {
  251. $data['@'.$attr->nodeName] = (int) $attr->nodeValue;
  252. } else {
  253. $data['@'.$attr->nodeName] = $attr->nodeValue;
  254. }
  255. }
  256. return $data;
  257. }
  258. /**
  259. * Parse the input DOMNode value (content and children) into an array or a string.
  260. *
  261. * @param \DOMNode $node xml to parse
  262. *
  263. * @return array|string
  264. */
  265. private function parseXmlValue(\DOMNode $node)
  266. {
  267. if (!$node->hasChildNodes()) {
  268. return $node->nodeValue;
  269. }
  270. if (1 === $node->childNodes->length && in_array($node->firstChild->nodeType, array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE))) {
  271. return $node->firstChild->nodeValue;
  272. }
  273. $value = array();
  274. foreach ($node->childNodes as $subnode) {
  275. $val = $this->parseXml($subnode);
  276. if ('item' === $subnode->nodeName && isset($val['@key'])) {
  277. if (isset($val['#'])) {
  278. $value[$val['@key']] = $val['#'];
  279. } else {
  280. $value[$val['@key']] = $val;
  281. }
  282. } else {
  283. $value[$subnode->nodeName][] = $val;
  284. }
  285. }
  286. foreach ($value as $key => $val) {
  287. if (is_array($val) && 1 === count($val)) {
  288. $value[$key] = current($val);
  289. }
  290. }
  291. return $value;
  292. }
  293. /**
  294. * Parse the data and convert it to DOMElements.
  295. *
  296. * @param \DOMNode $parentNode
  297. * @param array|object $data
  298. * @param string|null $xmlRootNodeName
  299. *
  300. * @return bool
  301. *
  302. * @throws UnexpectedValueException
  303. */
  304. private function buildXml(\DOMNode $parentNode, $data, $xmlRootNodeName = null)
  305. {
  306. $append = true;
  307. if (is_array($data) || ($data instanceof \Traversable && !$this->serializer->supportsNormalization($data, $this->format))) {
  308. foreach ($data as $key => $data) {
  309. //Ah this is the magic @ attribute types.
  310. if (0 === strpos($key, '@') && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key, 1))) {
  311. $parentNode->setAttribute($attributeName, $data);
  312. } elseif ($key === '#') {
  313. $append = $this->selectNodeType($parentNode, $data);
  314. } elseif (is_array($data) && false === is_numeric($key)) {
  315. // Is this array fully numeric keys?
  316. if (ctype_digit(implode('', array_keys($data)))) {
  317. /*
  318. * Create nodes to append to $parentNode based on the $key of this array
  319. * Produces <xml><item>0</item><item>1</item></xml>
  320. * From array("item" => array(0,1));.
  321. */
  322. foreach ($data as $subData) {
  323. $append = $this->appendNode($parentNode, $subData, $key);
  324. }
  325. } else {
  326. $append = $this->appendNode($parentNode, $data, $key);
  327. }
  328. } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
  329. $append = $this->appendNode($parentNode, $data, 'item', $key);
  330. } else {
  331. $append = $this->appendNode($parentNode, $data, $key);
  332. }
  333. }
  334. return $append;
  335. }
  336. if (is_object($data)) {
  337. $data = $this->serializer->normalize($data, $this->format, $this->context);
  338. if (null !== $data && !is_scalar($data)) {
  339. return $this->buildXml($parentNode, $data, $xmlRootNodeName);
  340. }
  341. // top level data object was normalized into a scalar
  342. if (!$parentNode->parentNode->parentNode) {
  343. $root = $parentNode->parentNode;
  344. $root->removeChild($parentNode);
  345. return $this->appendNode($root, $data, $xmlRootNodeName);
  346. }
  347. return $this->appendNode($parentNode, $data, 'data');
  348. }
  349. throw new UnexpectedValueException(sprintf('An unexpected value could not be serialized: %s', var_export($data, true)));
  350. }
  351. /**
  352. * Selects the type of node to create and appends it to the parent.
  353. *
  354. * @param \DOMNode $parentNode
  355. * @param array|object $data
  356. * @param string $nodeName
  357. * @param string $key
  358. *
  359. * @return bool
  360. */
  361. private function appendNode(\DOMNode $parentNode, $data, $nodeName, $key = null)
  362. {
  363. $node = $this->dom->createElement($nodeName);
  364. if (null !== $key) {
  365. $node->setAttribute('key', $key);
  366. }
  367. $appendNode = $this->selectNodeType($node, $data);
  368. // we may have decided not to append this node, either in error or if its $nodeName is not valid
  369. if ($appendNode) {
  370. $parentNode->appendChild($node);
  371. }
  372. return $appendNode;
  373. }
  374. /**
  375. * Checks if a value contains any characters which would require CDATA wrapping.
  376. *
  377. * @param string $val
  378. *
  379. * @return bool
  380. */
  381. private function needsCdataWrapping($val)
  382. {
  383. return preg_match('/[<>&]/', $val);
  384. }
  385. /**
  386. * Tests the value being passed and decide what sort of element to create.
  387. *
  388. * @param \DOMNode $node
  389. * @param mixed $val
  390. *
  391. * @return bool
  392. *
  393. * @throws UnexpectedValueException
  394. */
  395. private function selectNodeType(\DOMNode $node, $val)
  396. {
  397. if (is_array($val)) {
  398. return $this->buildXml($node, $val);
  399. } elseif ($val instanceof \SimpleXMLElement) {
  400. $child = $this->dom->importNode(dom_import_simplexml($val), true);
  401. $node->appendChild($child);
  402. } elseif ($val instanceof \Traversable) {
  403. $this->buildXml($node, $val);
  404. } elseif (is_object($val)) {
  405. return $this->buildXml($node, $this->serializer->normalize($val, $this->format, $this->context));
  406. } elseif (is_numeric($val)) {
  407. return $this->appendText($node, (string) $val);
  408. } elseif (is_string($val) && $this->needsCdataWrapping($val)) {
  409. return $this->appendCData($node, $val);
  410. } elseif (is_string($val)) {
  411. return $this->appendText($node, $val);
  412. } elseif (is_bool($val)) {
  413. return $this->appendText($node, (int) $val);
  414. } elseif ($val instanceof \DOMNode) {
  415. $child = $this->dom->importNode($val, true);
  416. $node->appendChild($child);
  417. }
  418. return true;
  419. }
  420. /**
  421. * Get real XML root node name, taking serializer options into account.
  422. *
  423. * @param array $context
  424. *
  425. * @return string
  426. */
  427. private function resolveXmlRootName(array $context = array())
  428. {
  429. return isset($context['xml_root_node_name'])
  430. ? $context['xml_root_node_name']
  431. : $this->rootNodeName;
  432. }
  433. /**
  434. * Create a DOM document, taking serializer options into account.
  435. *
  436. * @param array $context options that the encoder has access to
  437. *
  438. * @return \DOMDocument
  439. */
  440. private function createDomDocument(array $context)
  441. {
  442. $document = new \DOMDocument();
  443. // Set an attribute on the DOM document specifying, as part of the XML declaration,
  444. $xmlOptions = array(
  445. // nicely formats output with indentation and extra space
  446. 'xml_format_output' => 'formatOutput',
  447. // the version number of the document
  448. 'xml_version' => 'xmlVersion',
  449. // the encoding of the document
  450. 'xml_encoding' => 'encoding',
  451. // whether the document is standalone
  452. 'xml_standalone' => 'xmlStandalone',
  453. );
  454. foreach ($xmlOptions as $xmlOption => $documentProperty) {
  455. if (isset($context[$xmlOption])) {
  456. $document->$documentProperty = $context[$xmlOption];
  457. }
  458. }
  459. return $document;
  460. }
  461. }