XmlEncoder.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. /*
  3. * Portions of this code where received from the Symfony framework under the
  4. * MIT license. All other code is Copyright 2011 Johannes M. Schmitt
  5. * <schmittjoh@gmail.com> and released under the following license:
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. namespace JMS\SerializerBundle\Serializer\Encoder;
  20. /**
  21. * Encodes, and decodes XML data
  22. *
  23. * @author Jordi Boggiano <j.boggiano@seld.be>
  24. * @author John Wards <jwards@whiteoctober.co.uk>
  25. * @author Fabian Vogler <fabian@equivalence.ch>
  26. */
  27. class XmlEncoder implements EncoderInterface
  28. {
  29. private $dom;
  30. private $version;
  31. private $encoding;
  32. private $rootNodeName;
  33. public function __construct($version = '1.0', $encoding = 'utf-8', $rootNodeName = 'response')
  34. {
  35. $this->version = $version;
  36. $this->encoding = $encoding;
  37. $this->rootNodeName = $rootNodeName;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function encode($data)
  43. {
  44. if ($data instanceof \DOMDocument) {
  45. $data->encoding = $this->encoding;
  46. return $data->saveXML();
  47. }
  48. $this->dom = new \DOMDocument($this->version, $this->encoding);
  49. if (null !== $data && !is_scalar($data)) {
  50. $root = $this->dom->createElement($this->rootNodeName);
  51. $this->dom->appendChild($root);
  52. $this->buildXml($root, $data);
  53. } else {
  54. $this->appendNode($this->dom, $data, $this->rootNodeName);
  55. }
  56. return $this->dom->saveXML();
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function decode($data)
  62. {
  63. $xml = simplexml_load_string($data);
  64. if (!$xml->count()) {
  65. if (!$xml->attributes()) {
  66. return (string) $xml;
  67. }
  68. $data = array();
  69. foreach ($xml->attributes() as $attrkey => $attr) {
  70. $data['@'.$attrkey] = (string) $attr;
  71. }
  72. $data['#'] = (string) $xml;
  73. return $data;
  74. }
  75. return $this->parseXml($xml);
  76. }
  77. /**
  78. * @param DOMNode $node
  79. * @param string $val
  80. * @return Boolean
  81. */
  82. final protected function appendXMLString($node, $val)
  83. {
  84. if (strlen($val) > 0) {
  85. $frag = $this->dom->createDocumentFragment();
  86. $frag->appendXML($val);
  87. $node->appendChild($frag);
  88. return true;
  89. }
  90. return false;
  91. }
  92. /**
  93. * @param DOMNode $node
  94. * @param string $val
  95. * @return Boolean
  96. */
  97. final protected function appendText($node, $val)
  98. {
  99. $nodeText = $this->dom->createTextNode($val);
  100. $node->appendChild($nodeText);
  101. return true;
  102. }
  103. /**
  104. * @param DOMNode $node
  105. * @param string $val
  106. * @return Boolean
  107. */
  108. final protected function appendCData($node, $val)
  109. {
  110. $nodeText = $this->dom->createCDATASection($val);
  111. $node->appendChild($nodeText);
  112. return true;
  113. }
  114. /**
  115. * @param DOMNode $node
  116. * @param DOMDocumentFragment $fragment
  117. * @return Boolean
  118. */
  119. final protected function appendDocumentFragment($node, $fragment)
  120. {
  121. if ($fragment instanceof \DOMDocumentFragment) {
  122. $node->appendChild($fragment);
  123. return true;
  124. }
  125. return false;
  126. }
  127. /**
  128. * Checks the name is a valid xml element name
  129. * @param string $name
  130. * @return Boolean
  131. */
  132. final protected function isElementNameValid($name)
  133. {
  134. return $name &&
  135. false === strpos($name, ' ') &&
  136. preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  137. }
  138. /**
  139. * Parse the input SimpleXmlElement into an array
  140. *
  141. * @param SimpleXmlElement $node xml to parse
  142. * @return array
  143. */
  144. private function parseXml($node)
  145. {
  146. $data = array();
  147. if ($node->attributes()) {
  148. foreach ($node->attributes() as $attrkey => $attr) {
  149. $data['@'.$attrkey] = (string) $attr;
  150. }
  151. }
  152. foreach ($node->children() as $key => $subnode) {
  153. if ($subnode->count()) {
  154. $value = $this->parseXml($subnode);
  155. } elseif ($subnode->attributes()) {
  156. $value = array();
  157. foreach ($subnode->attributes() as $attrkey => $attr) {
  158. $value['@'.$attrkey] = (string) $attr;
  159. }
  160. $value['#'] = (string) $subnode;
  161. } else {
  162. $value = (string) $subnode;
  163. }
  164. if ($key === 'item') {
  165. if (isset($value['@key'])) {
  166. $data[(string)$value['@key']] = $value['#'];
  167. } elseif (isset($data['item'])) {
  168. $tmp = $data['item'];
  169. unset($data['item']);
  170. $data[] = $tmp;
  171. $data[] = $value;
  172. }
  173. } elseif (key_exists($key, $data)) {
  174. if ((false === is_array($data[$key])) || (false === isset($data[$key][0]))) {
  175. $data[$key] = array($data[$key]);
  176. }
  177. $data[$key][] = $value;
  178. } else {
  179. $data[$key] = $value;
  180. }
  181. }
  182. return $data;
  183. }
  184. /**
  185. * Parse the data and convert it to DOMElements
  186. *
  187. * @param DOMNode $parentNode
  188. * @param array|object $data data
  189. * @return Boolean
  190. */
  191. private function buildXml($parentNode, $data)
  192. {
  193. $append = true;
  194. if (is_array($data) || $data instanceof \Traversable) {
  195. foreach ($data as $key => $data) {
  196. //Ah this is the magic @ attribute types.
  197. if (0 === strpos($key, "@") && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key,1))) {
  198. $parentNode->setAttribute($attributeName, $data);
  199. } elseif ($key === '#') {
  200. $append = $this->selectNodeType($parentNode, $data);
  201. } elseif (is_array($data) && false === is_numeric($key)) {
  202. /**
  203. * Is this array fully numeric keys?
  204. */
  205. if (ctype_digit(implode('', array_keys($data)))) {
  206. /**
  207. * Create nodes to append to $parentNode based on the $key of this array
  208. * Produces <xml><item>0</item><item>1</item></xml>
  209. * From array("item" => array(0,1));
  210. */
  211. foreach ($data as $subData) {
  212. $append = $this->appendNode($parentNode, $subData, $key);
  213. }
  214. } else {
  215. $append = $this->appendNode($parentNode, $data, $key);
  216. }
  217. } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
  218. $append = $this->appendNode($parentNode, $data, "item", $key);
  219. } else {
  220. $append = $this->appendNode($parentNode, $data, $key);
  221. }
  222. }
  223. return $append;
  224. }
  225. throw new \UnexpectedValueException('An unexpected value could not be serialized: '.var_export($data, true));
  226. }
  227. /**
  228. * Selects the type of node to create and appends it to the parent.
  229. *
  230. * @param DOMNode $parentNode
  231. * @param array|object $data
  232. * @param string $nodename
  233. * @param string $key
  234. * @return void
  235. */
  236. private function appendNode($parentNode, $data, $nodeName, $key = null)
  237. {
  238. $node = $this->dom->createElement($nodeName);
  239. if (null !== $key) {
  240. $node->setAttribute('key', $key);
  241. }
  242. $appendNode = $this->selectNodeType($node, $data);
  243. // we may have decided not to append this node, either in error or if its $nodeName is not valid
  244. if ($appendNode) {
  245. $parentNode->appendChild($node);
  246. }
  247. return $appendNode;
  248. }
  249. /**
  250. * Tests the value being passed and decide what sort of element to create
  251. *
  252. * @param DOMNode $node
  253. * @param mixed $val
  254. * @return Boolean
  255. */
  256. private function selectNodeType($node, $val)
  257. {
  258. if (is_array($val)) {
  259. return $this->buildXml($node, $val);
  260. } elseif ($val instanceof \SimpleXMLElement) {
  261. $child = $this->dom->importNode(dom_import_simplexml($val), true);
  262. $node->appendChild($child);
  263. } elseif ($val instanceof \Traversable) {
  264. $this->buildXml($node, $val);
  265. } elseif (is_numeric($val)) {
  266. return $this->appendText($node, (string) $val);
  267. } elseif (is_string($val)) {
  268. return $this->appendCData($node, $val);
  269. } elseif (is_bool($val)) {
  270. return $this->appendText($node, (int) $val);
  271. } elseif ($val instanceof \DOMNode) {
  272. $child = $this->dom->importNode($val, true);
  273. $node->appendChild($child);
  274. }
  275. return true;
  276. }
  277. }