XmlEncoder.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. namespace Symfony\Component\Serializer\Encoder;
  3. use Symfony\Component\Serializer\SerializerInterface;
  4. /*
  5. * This file is part of the Symfony framework.
  6. *
  7. * (c) Fabien Potencier <fabien@symfony.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  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. */
  19. class XmlEncoder extends AbstractEncoder
  20. {
  21. private $dom;
  22. private $format;
  23. private $rootNodeName = 'response';
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function encode($data, $format)
  28. {
  29. if ($data instanceof \DOMDocument) {
  30. return $data->saveXML();
  31. }
  32. $this->dom = new \DOMDocument();
  33. $this->format = $format;
  34. if ($this->serializer->isStructuredType($data)) {
  35. $root = $this->dom->createElement($this->rootNodeName);
  36. $this->dom->appendChild($root);
  37. $this->buildXml($root, $data);
  38. } else {
  39. $this->appendNode($this->dom, $data, $this->rootNodeName);
  40. }
  41. return $this->dom->saveXML();
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function decode($data, $format)
  47. {
  48. $xml = simplexml_load_string($data);
  49. if (!$xml->count()) {
  50. return (string) $xml;
  51. }
  52. return $this->parseXml($xml);
  53. }
  54. /**
  55. * Sets the root node name
  56. * @param string $name root node name
  57. */
  58. public function setRootNodeName($name)
  59. {
  60. $this->rootNodeName = $name;
  61. }
  62. /**
  63. * Returns the root node name
  64. * @return string
  65. */
  66. public function getRootNodeName()
  67. {
  68. return $this->rootNodeName;
  69. }
  70. /**
  71. * @param DOMNode $node
  72. * @param string $val
  73. * @return Boolean
  74. */
  75. final protected function appendXMLString($node, $val)
  76. {
  77. if (strlen($val) > 0) {
  78. $frag = $this->dom->createDocumentFragment();
  79. $frag->appendXML($val);
  80. $node->appendChild($frag);
  81. return true;
  82. }
  83. return false;
  84. }
  85. /**
  86. * @param DOMNode $node
  87. * @param string $val
  88. * @return Boolean
  89. */
  90. final protected function appendText($node, $val)
  91. {
  92. $nodeText = $this->dom->createTextNode($val);
  93. $node->appendChild($nodeText);
  94. return true;
  95. }
  96. /**
  97. * @param DOMNode $node
  98. * @param string $val
  99. * @return Boolean
  100. */
  101. final protected function appendCData($node, $val)
  102. {
  103. $nodeText = $this->dom->createCDATASection($val);
  104. $node->appendChild($nodeText);
  105. return true;
  106. }
  107. /**
  108. * @param DOMNode $node
  109. * @param DOMDocumentFragment $fragment
  110. * @return Boolean
  111. */
  112. final protected function appendDocumentFragment($node, $fragment)
  113. {
  114. if ($fragment instanceof \DOMDocumentFragment) {
  115. $node->appendChild($fragment);
  116. return true;
  117. }
  118. return false;
  119. }
  120. /**
  121. * Checks the name is avalid xml element name
  122. * @param string $name
  123. * @return Boolean
  124. */
  125. final protected function isElementNameValid($name)
  126. {
  127. return $name &&
  128. false === strpos($name, ' ') &&
  129. preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  130. }
  131. /**
  132. * Parse the input SimpleXmlElement into an array
  133. *
  134. * @param SimpleXmlElement $node xml to parse
  135. * @return array
  136. */
  137. private function parseXml($node)
  138. {
  139. $data = array();
  140. foreach ($node->children() as $key => $subnode) {
  141. if ($subnode->count()) {
  142. $value = $this->parseXml($subnode);
  143. if ($subnode->attributes()) {
  144. foreach ($subnode->attributes() as $attrkey => $attr) {
  145. $value['@'.$attrkey] = (string) $attr;
  146. }
  147. }
  148. } else {
  149. $value = (string) $subnode;
  150. }
  151. if ($key === 'item') {
  152. if (isset($subnode['key'])) {
  153. $data[(string)$subnode['key']] = $value;
  154. } elseif (isset($data['item'])) {
  155. $tmp = $data['item'];
  156. unset($data['item']);
  157. $data[] = $tmp;
  158. $data[] = $value;
  159. }
  160. } elseif (key_exists($key, $data)) {
  161. if (false === is_array($data[$key])) {
  162. $data[$key] = array($data[$key]);
  163. }
  164. $data[$key][] = $value;
  165. } else {
  166. $data[$key] = $value;
  167. }
  168. }
  169. return $data;
  170. }
  171. /**
  172. * Parse the data and convert it to DOMElements
  173. *
  174. * @param DOMNode $parentNode
  175. * @param array|object $data data
  176. * @return bool
  177. */
  178. private function buildXml($parentNode, $data)
  179. {
  180. $append = true;
  181. if (is_array($data) || $data instanceof \Traversable) {
  182. foreach ($data as $key => $data) {
  183. //Ah this is the magic @ attribute types.
  184. if (0 === strpos($key, "@") && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key,1))) {
  185. $parentNode->setAttribute($attributeName, $data);
  186. } elseif (is_array($data) && false === is_numeric($key)) {
  187. /**
  188. * Is this array fully numeric keys?
  189. */
  190. if (ctype_digit(implode('', array_keys($data)))) {
  191. /**
  192. * Create nodes to append to $parentNode based on the $key of this array
  193. * Produces <xml><item>0</item><item>1</item></xml>
  194. * From array("item" => array(0,1));
  195. */
  196. foreach ($data as $subData) {
  197. $append = $this->appendNode($parentNode, $subData, $key);
  198. }
  199. } else {
  200. $append = $this->appendNode($parentNode, $data, $key);
  201. }
  202. } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
  203. $append = $this->appendNode($parentNode, $data, "item", $key);
  204. } else {
  205. $append = $this->appendNode($parentNode, $data, $key);
  206. }
  207. }
  208. return $append;
  209. }
  210. if (is_object($data)) {
  211. $data = $this->serializer->normalizeObject($data, $this->format);
  212. if (!$this->serializer->isStructuredType($data)) {
  213. // top level data object is normalized into a scalar
  214. if (!$parentNode->parentNode->parentNode) {
  215. $root = $parentNode->parentNode;
  216. $root->removeChild($parentNode);
  217. return $this->appendNode($root, $data, $this->rootNodeName);
  218. }
  219. return $this->appendNode($parentNode, $data, 'data');
  220. }
  221. return $this->buildXml($parentNode, $data);
  222. }
  223. throw new \UnexpectedValueException('An unexpected value could not be serialized: '.var_export($data, true));
  224. }
  225. /**
  226. * Selects the type of node to create and appends it to the parent.
  227. *
  228. * @param $parentNode
  229. * @param $data
  230. * @param $nodename
  231. * @return void
  232. */
  233. private function appendNode($parentNode, $data, $nodeName, $key = null)
  234. {
  235. $node = $this->dom->createElement($nodeName);
  236. if (null !== $key) {
  237. $node->setAttribute('key', $key);
  238. }
  239. $appendNode = $this->selectNodeType($node, $data);
  240. // we may have decided not to append this node, either in error or if its $nodeName is not valid
  241. if ($appendNode) {
  242. $parentNode->appendChild($node);
  243. }
  244. return $appendNode;
  245. }
  246. /**
  247. * Tests the value being passed and decide what sort of element to create
  248. *
  249. * @param DOMNode $node
  250. * @param mixed $val
  251. * @return Boolean
  252. */
  253. private function selectNodeType($node, $val)
  254. {
  255. if (is_array($val)) {
  256. return $this->buildXml($node, $val);
  257. } elseif ($val instanceof \SimpleXMLElement) {
  258. $child = $this->dom->importNode(dom_import_simplexml($val), true);
  259. $node->appendChild($child);
  260. } elseif ($val instanceof \Traversable) {
  261. $this->buildXml($node, $val);
  262. } elseif (is_object($val)) {
  263. return $this->buildXml($node, $this->serializer->normalizeObject($val, $this->format));
  264. } elseif (is_numeric($val)) {
  265. return $this->appendText($node, (string) $val);
  266. } elseif (is_string($val)) {
  267. return $this->appendCData($node, $val);
  268. } elseif (is_bool($val)) {
  269. return $this->appendText($node, (int) $val);
  270. } elseif ($val instanceof \DOMNode) {
  271. $child = $this->dom->importNode($val, true);
  272. $node->appendChild($child);
  273. }
  274. return true;
  275. }
  276. }