XmlEncoder.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. public function supportsEncoding($data)
  78. {
  79. return true;
  80. }
  81. public function supportsDecoding($data)
  82. {
  83. return true;
  84. }
  85. /**
  86. * @param DOMNode $node
  87. * @param string $val
  88. * @return Boolean
  89. */
  90. final protected function appendXMLString($node, $val)
  91. {
  92. if (strlen($val) > 0) {
  93. $frag = $this->dom->createDocumentFragment();
  94. $frag->appendXML($val);
  95. $node->appendChild($frag);
  96. return true;
  97. }
  98. return false;
  99. }
  100. /**
  101. * @param DOMNode $node
  102. * @param string $val
  103. * @return Boolean
  104. */
  105. final protected function appendText($node, $val)
  106. {
  107. $nodeText = $this->dom->createTextNode($val);
  108. $node->appendChild($nodeText);
  109. return true;
  110. }
  111. /**
  112. * @param DOMNode $node
  113. * @param string $val
  114. * @return Boolean
  115. */
  116. final protected function appendCData($node, $val)
  117. {
  118. $nodeText = $this->dom->createCDATASection($val);
  119. $node->appendChild($nodeText);
  120. return true;
  121. }
  122. /**
  123. * @param DOMNode $node
  124. * @param DOMDocumentFragment $fragment
  125. * @return Boolean
  126. */
  127. final protected function appendDocumentFragment($node, $fragment)
  128. {
  129. if ($fragment instanceof \DOMDocumentFragment) {
  130. $node->appendChild($fragment);
  131. return true;
  132. }
  133. return false;
  134. }
  135. /**
  136. * Checks the name is a valid xml element name
  137. * @param string $name
  138. * @return Boolean
  139. */
  140. final protected function isElementNameValid($name)
  141. {
  142. return $name &&
  143. false === strpos($name, ' ') &&
  144. preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  145. }
  146. /**
  147. * Parse the input SimpleXmlElement into an array
  148. *
  149. * @param SimpleXmlElement $node xml to parse
  150. * @return array
  151. */
  152. private function parseXml($node)
  153. {
  154. $data = array();
  155. if ($node->attributes()) {
  156. foreach ($node->attributes() as $attrkey => $attr) {
  157. $data['@'.$attrkey] = (string) $attr;
  158. }
  159. }
  160. foreach ($node->children() as $key => $subnode) {
  161. if ($subnode->count()) {
  162. $value = $this->parseXml($subnode);
  163. } elseif ($subnode->attributes()) {
  164. $value = array();
  165. foreach ($subnode->attributes() as $attrkey => $attr) {
  166. $value['@'.$attrkey] = (string) $attr;
  167. }
  168. $value['#'] = (string) $subnode;
  169. } else {
  170. $value = (string) $subnode;
  171. }
  172. if ($key === 'item') {
  173. if (isset($value['@key'])) {
  174. $data[(string)$value['@key']] = $value['#'];
  175. } elseif (isset($data['item'])) {
  176. $tmp = $data['item'];
  177. unset($data['item']);
  178. $data[] = $tmp;
  179. $data[] = $value;
  180. }
  181. } elseif (key_exists($key, $data)) {
  182. if ((false === is_array($data[$key])) || (false === isset($data[$key][0]))) {
  183. $data[$key] = array($data[$key]);
  184. }
  185. $data[$key][] = $value;
  186. } else {
  187. $data[$key] = $value;
  188. }
  189. }
  190. return $data;
  191. }
  192. /**
  193. * Parse the data and convert it to DOMElements
  194. *
  195. * @param DOMNode $parentNode
  196. * @param array|object $data data
  197. * @return Boolean
  198. */
  199. private function buildXml($parentNode, $data)
  200. {
  201. $append = true;
  202. if (is_array($data) || $data instanceof \Traversable) {
  203. foreach ($data as $key => $data) {
  204. //Ah this is the magic @ attribute types.
  205. if (0 === strpos($key, "@") && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key,1))) {
  206. $parentNode->setAttribute($attributeName, $data);
  207. } elseif ($key === '#') {
  208. $append = $this->selectNodeType($parentNode, $data);
  209. } elseif (is_array($data) && false === is_numeric($key)) {
  210. /**
  211. * Is this array fully numeric keys?
  212. */
  213. if (ctype_digit(implode('', array_keys($data)))) {
  214. /**
  215. * Create nodes to append to $parentNode based on the $key of this array
  216. * Produces <xml><item>0</item><item>1</item></xml>
  217. * From array("item" => array(0,1));
  218. */
  219. foreach ($data as $subData) {
  220. $append = $this->appendNode($parentNode, $subData, $key);
  221. }
  222. } else {
  223. $append = $this->appendNode($parentNode, $data, $key);
  224. }
  225. } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
  226. $append = $this->appendNode($parentNode, $data, "item", $key);
  227. } else {
  228. $append = $this->appendNode($parentNode, $data, $key);
  229. }
  230. }
  231. return $append;
  232. }
  233. throw new \UnexpectedValueException('An unexpected value could not be serialized: '.var_export($data, true));
  234. }
  235. /**
  236. * Selects the type of node to create and appends it to the parent.
  237. *
  238. * @param DOMNode $parentNode
  239. * @param array|object $data
  240. * @param string $nodename
  241. * @param string $key
  242. * @return void
  243. */
  244. private function appendNode($parentNode, $data, $nodeName, $key = null)
  245. {
  246. $node = $this->dom->createElement($nodeName);
  247. if (null !== $key) {
  248. $node->setAttribute('key', $key);
  249. }
  250. $appendNode = $this->selectNodeType($node, $data);
  251. // we may have decided not to append this node, either in error or if its $nodeName is not valid
  252. if ($appendNode) {
  253. $parentNode->appendChild($node);
  254. }
  255. return $appendNode;
  256. }
  257. /**
  258. * Tests the value being passed and decide what sort of element to create
  259. *
  260. * @param DOMNode $node
  261. * @param mixed $val
  262. * @return Boolean
  263. */
  264. private function selectNodeType($node, $val)
  265. {
  266. if (is_array($val)) {
  267. return $this->buildXml($node, $val);
  268. } elseif ($val instanceof \SimpleXMLElement) {
  269. $child = $this->dom->importNode(dom_import_simplexml($val), true);
  270. $node->appendChild($child);
  271. } elseif ($val instanceof \Traversable) {
  272. $this->buildXml($node, $val);
  273. } elseif (is_numeric($val)) {
  274. return $this->appendText($node, (string) $val);
  275. } elseif (is_string($val)) {
  276. return $this->appendCData($node, $val);
  277. } elseif (is_bool($val)) {
  278. return $this->appendText($node, (int) $val);
  279. } elseif ($val instanceof \DOMNode) {
  280. $child = $this->dom->importNode($val, true);
  281. $node->appendChild($child);
  282. }
  283. return true;
  284. }
  285. }