PageRenderTime 60ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/XmlEncoder.php

https://bitbucket.org/thxer/5netproba
PHP | 429 lines | 240 code | 52 blank | 137 comment | 41 complexity | fe00a2a2046326729ddaef256d9a76f1 MD5 | raw file
  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. */
  19. class XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, DecoderInterface, NormalizationAwareInterface
  20. {
  21. private $dom;
  22. private $format;
  23. private $rootNodeName = 'response';
  24. /**
  25. * Construct new XmlEncoder and allow to change the root node element name.
  26. *
  27. * @param string $rootNodeName
  28. */
  29. public function __construct($rootNodeName = 'response')
  30. {
  31. $this->rootNodeName = $rootNodeName;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function encode($data, $format, array $context = array())
  37. {
  38. if ($data instanceof \DOMDocument) {
  39. return $data->saveXML();
  40. }
  41. $xmlRootNodeName = $this->resolveXmlRootName($context);
  42. $this->dom = new \DOMDocument();
  43. $this->format = $format;
  44. if (null !== $data && !is_scalar($data)) {
  45. $root = $this->dom->createElement($xmlRootNodeName);
  46. $this->dom->appendChild($root);
  47. $this->buildXml($root, $data, $xmlRootNodeName);
  48. } else {
  49. $this->appendNode($this->dom, $data, $xmlRootNodeName);
  50. }
  51. return $this->dom->saveXML();
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function decode($data, $format, array $context = array())
  57. {
  58. $internalErrors = libxml_use_internal_errors(true);
  59. $disableEntities = libxml_disable_entity_loader(true);
  60. libxml_clear_errors();
  61. $dom = new \DOMDocument();
  62. $dom->loadXML($data, LIBXML_NONET);
  63. libxml_use_internal_errors($internalErrors);
  64. libxml_disable_entity_loader($disableEntities);
  65. foreach ($dom->childNodes as $child) {
  66. if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
  67. throw new UnexpectedValueException('Document types are not allowed.');
  68. }
  69. }
  70. $xml = simplexml_import_dom($dom);
  71. if ($error = libxml_get_last_error()) {
  72. throw new UnexpectedValueException($error->message);
  73. }
  74. if (!$xml->count()) {
  75. if (!$xml->attributes()) {
  76. return (string) $xml;
  77. }
  78. $data = array();
  79. foreach ($xml->attributes() as $attrkey => $attr) {
  80. $data['@'.$attrkey] = (string) $attr;
  81. }
  82. $data['#'] = (string) $xml;
  83. return $data;
  84. }
  85. return $this->parseXml($xml);
  86. }
  87. /**
  88. * Checks whether the serializer can encode to given format
  89. *
  90. * @param string $format format name
  91. *
  92. * @return Boolean
  93. */
  94. public function supportsEncoding($format)
  95. {
  96. return 'xml' === $format;
  97. }
  98. /**
  99. * Checks whether the serializer can decode from given format
  100. *
  101. * @param string $format format name
  102. *
  103. * @return Boolean
  104. */
  105. public function supportsDecoding($format)
  106. {
  107. return 'xml' === $format;
  108. }
  109. /**
  110. * Sets the root node name
  111. *
  112. * @param string $name root node name
  113. */
  114. public function setRootNodeName($name)
  115. {
  116. $this->rootNodeName = $name;
  117. }
  118. /**
  119. * Returns the root node name
  120. * @return string
  121. */
  122. public function getRootNodeName()
  123. {
  124. return $this->rootNodeName;
  125. }
  126. /**
  127. * @param DOMNode $node
  128. * @param string $val
  129. *
  130. * @return Boolean
  131. */
  132. final protected function appendXMLString($node, $val)
  133. {
  134. if (strlen($val) > 0) {
  135. $frag = $this->dom->createDocumentFragment();
  136. $frag->appendXML($val);
  137. $node->appendChild($frag);
  138. return true;
  139. }
  140. return false;
  141. }
  142. /**
  143. * @param DOMNode $node
  144. * @param string $val
  145. *
  146. * @return Boolean
  147. */
  148. final protected function appendText($node, $val)
  149. {
  150. $nodeText = $this->dom->createTextNode($val);
  151. $node->appendChild($nodeText);
  152. return true;
  153. }
  154. /**
  155. * @param DOMNode $node
  156. * @param string $val
  157. *
  158. * @return Boolean
  159. */
  160. final protected function appendCData($node, $val)
  161. {
  162. $nodeText = $this->dom->createCDATASection($val);
  163. $node->appendChild($nodeText);
  164. return true;
  165. }
  166. /**
  167. * @param DOMNode $node
  168. * @param DOMDocumentFragment $fragment
  169. *
  170. * @return Boolean
  171. */
  172. final protected function appendDocumentFragment($node, $fragment)
  173. {
  174. if ($fragment instanceof \DOMDocumentFragment) {
  175. $node->appendChild($fragment);
  176. return true;
  177. }
  178. return false;
  179. }
  180. /**
  181. * Checks the name is a valid xml element name
  182. *
  183. * @param string $name
  184. *
  185. * @return Boolean
  186. */
  187. final protected function isElementNameValid($name)
  188. {
  189. return $name &&
  190. false === strpos($name, ' ') &&
  191. preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  192. }
  193. /**
  194. * Parse the input SimpleXmlElement into an array.
  195. *
  196. * @param SimpleXmlElement $node xml to parse
  197. *
  198. * @return array
  199. */
  200. private function parseXml($node)
  201. {
  202. $data = array();
  203. if ($node->attributes()) {
  204. foreach ($node->attributes() as $attrkey => $attr) {
  205. $data['@'.$attrkey] = (string) $attr;
  206. }
  207. }
  208. foreach ($node->children() as $key => $subnode) {
  209. if ($subnode->count()) {
  210. $value = $this->parseXml($subnode);
  211. } elseif ($subnode->attributes()) {
  212. $value = array();
  213. foreach ($subnode->attributes() as $attrkey => $attr) {
  214. $value['@'.$attrkey] = (string) $attr;
  215. }
  216. $value['#'] = (string) $subnode;
  217. } else {
  218. $value = (string) $subnode;
  219. }
  220. if ($key === 'item') {
  221. if (isset($value['@key'])) {
  222. if (isset($value['#'])) {
  223. $data[(string) $value['@key']] = $value['#'];
  224. } else {
  225. $data[(string) $value['@key']] = $value;
  226. }
  227. } else {
  228. $data['item'][] = $value;
  229. }
  230. } elseif (array_key_exists($key, $data) || $key == "entry") {
  231. if ((false === is_array($data[$key])) || (false === isset($data[$key][0]))) {
  232. $data[$key] = array($data[$key]);
  233. }
  234. $data[$key][] = $value;
  235. } else {
  236. $data[$key] = $value;
  237. }
  238. }
  239. return $data;
  240. }
  241. /**
  242. * Parse the data and convert it to DOMElements
  243. *
  244. * @param DOMNode $parentNode
  245. * @param array|object $data data
  246. * @param string $xmlRootNodeName
  247. *
  248. * @return Boolean
  249. *
  250. * @throws UnexpectedValueException
  251. */
  252. private function buildXml($parentNode, $data, $xmlRootNodeName = null)
  253. {
  254. $append = true;
  255. if (is_array($data) || $data instanceof \Traversable) {
  256. foreach ($data as $key => $data) {
  257. //Ah this is the magic @ attribute types.
  258. if (0 === strpos($key, "@") && is_scalar($data) && $this->isElementNameValid($attributeName = substr($key, 1))) {
  259. $parentNode->setAttribute($attributeName, $data);
  260. } elseif ($key === '#') {
  261. $append = $this->selectNodeType($parentNode, $data);
  262. } elseif (is_array($data) && false === is_numeric($key)) {
  263. /**
  264. * Is this array fully numeric keys?
  265. */
  266. if (ctype_digit(implode('', array_keys($data)))) {
  267. /**
  268. * Create nodes to append to $parentNode based on the $key of this array
  269. * Produces <xml><item>0</item><item>1</item></xml>
  270. * From array("item" => array(0,1));
  271. */
  272. foreach ($data as $subData) {
  273. $append = $this->appendNode($parentNode, $subData, $key);
  274. }
  275. } else {
  276. $append = $this->appendNode($parentNode, $data, $key);
  277. }
  278. } elseif (is_numeric($key) || !$this->isElementNameValid($key)) {
  279. $append = $this->appendNode($parentNode, $data, "item", $key);
  280. } else {
  281. $append = $this->appendNode($parentNode, $data, $key);
  282. }
  283. }
  284. return $append;
  285. }
  286. if (is_object($data)) {
  287. $data = $this->serializer->normalize($data, $this->format);
  288. if (null !== $data && !is_scalar($data)) {
  289. return $this->buildXml($parentNode, $data, $xmlRootNodeName);
  290. }
  291. // top level data object was normalized into a scalar
  292. if (!$parentNode->parentNode->parentNode) {
  293. $root = $parentNode->parentNode;
  294. $root->removeChild($parentNode);
  295. return $this->appendNode($root, $data, $xmlRootNodeName);
  296. }
  297. return $this->appendNode($parentNode, $data, 'data');
  298. }
  299. throw new UnexpectedValueException('An unexpected value could not be serialized: '.var_export($data, true));
  300. }
  301. /**
  302. * Selects the type of node to create and appends it to the parent.
  303. *
  304. * @param DOMNode $parentNode
  305. * @param array|object $data
  306. * @param string $nodeName
  307. * @param string $key
  308. *
  309. * @return Boolean
  310. */
  311. private function appendNode($parentNode, $data, $nodeName, $key = null)
  312. {
  313. $node = $this->dom->createElement($nodeName);
  314. if (null !== $key) {
  315. $node->setAttribute('key', $key);
  316. }
  317. $appendNode = $this->selectNodeType($node, $data);
  318. // we may have decided not to append this node, either in error or if its $nodeName is not valid
  319. if ($appendNode) {
  320. $parentNode->appendChild($node);
  321. }
  322. return $appendNode;
  323. }
  324. /**
  325. * Checks if a value contains any characters which would require CDATA wrapping.
  326. *
  327. * @param string $val
  328. *
  329. * @return Boolean
  330. */
  331. private function needsCdataWrapping($val)
  332. {
  333. return preg_match('/[<>&]/', $val);
  334. }
  335. /**
  336. * Tests the value being passed and decide what sort of element to create
  337. *
  338. * @param DOMNode $node
  339. * @param mixed $val
  340. *
  341. * @return Boolean
  342. */
  343. private function selectNodeType($node, $val)
  344. {
  345. if (is_array($val)) {
  346. return $this->buildXml($node, $val);
  347. } elseif ($val instanceof \SimpleXMLElement) {
  348. $child = $this->dom->importNode(dom_import_simplexml($val), true);
  349. $node->appendChild($child);
  350. } elseif ($val instanceof \Traversable) {
  351. $this->buildXml($node, $val);
  352. } elseif (is_object($val)) {
  353. return $this->buildXml($node, $this->serializer->normalize($val, $this->format));
  354. } elseif (is_numeric($val)) {
  355. return $this->appendText($node, (string) $val);
  356. } elseif (is_string($val) && $this->needsCdataWrapping($val)) {
  357. return $this->appendCData($node, $val);
  358. } elseif (is_string($val)) {
  359. return $this->appendText($node, $val);
  360. } elseif (is_bool($val)) {
  361. return $this->appendText($node, (int) $val);
  362. } elseif ($val instanceof \DOMNode) {
  363. $child = $this->dom->importNode($val, true);
  364. $node->appendChild($child);
  365. }
  366. return true;
  367. }
  368. /**
  369. * Get real XML root node name, taking serializer options into account.
  370. */
  371. private function resolveXmlRootName(array $context = array())
  372. {
  373. return isset($context['xml_root_node_name'])
  374. ? $context['xml_root_node_name']
  375. : $this->rootNodeName;
  376. }
  377. }