XmlSerializationVisitor.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. /*
  3. * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com>
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace JMS\Serializer;
  18. use JMS\Serializer\Exception\RuntimeException;
  19. use JMS\Serializer\Metadata\ClassMetadata;
  20. use JMS\Serializer\Metadata\PropertyMetadata;
  21. /**
  22. * XmlSerializationVisitor.
  23. *
  24. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  25. */
  26. class XmlSerializationVisitor extends AbstractVisitor
  27. {
  28. public $document;
  29. private $navigator;
  30. private $defaultRootName = 'result';
  31. private $defaultVersion = '1.0';
  32. private $defaultEncoding = 'UTF-8';
  33. private $stack;
  34. private $metadataStack;
  35. private $currentNode;
  36. private $currentMetadata;
  37. private $hasValue;
  38. private $nullWasVisited;
  39. public function setDefaultRootName($name)
  40. {
  41. $this->defaultRootName = $name;
  42. }
  43. /**
  44. * @return boolean
  45. */
  46. public function hasDefaultRootName()
  47. {
  48. return 'result' === $this->defaultRootName;
  49. }
  50. public function setDefaultVersion($version)
  51. {
  52. $this->defaultVersion = $version;
  53. }
  54. public function setDefaultEncoding($encoding)
  55. {
  56. $this->defaultEncoding = $encoding;
  57. }
  58. public function setNavigator(GraphNavigator $navigator)
  59. {
  60. $this->navigator = $navigator;
  61. $this->document = null;
  62. $this->stack = new \SplStack;
  63. $this->metadataStack = new \SplStack;
  64. }
  65. public function getNavigator()
  66. {
  67. return $this->navigator;
  68. }
  69. public function visitNull($data, array $type, Context $context)
  70. {
  71. if (null === $this->document) {
  72. $this->document = $this->createDocument(null, null, true);
  73. $node = $this->document->createAttribute('xsi:nil');
  74. $node->value = 'true';
  75. $this->currentNode->appendChild($node);
  76. $this->attachNullNamespace();
  77. return;
  78. }
  79. $node = $this->document->createAttribute('xsi:nil');
  80. $node->value = 'true';
  81. $this->attachNullNamespace();
  82. return $node;
  83. }
  84. public function visitString($data, array $type, Context $context)
  85. {
  86. if (null !== $this->currentMetadata) {
  87. $doCData = $this->currentMetadata->xmlElementCData;
  88. } else {
  89. $doCData = true;
  90. }
  91. if (null === $this->document) {
  92. $this->document = $this->createDocument(null, null, true);
  93. $this->currentNode->appendChild($doCData ? $this->document->createCDATASection($data) : $this->document->createTextNode((string) $data));
  94. return;
  95. }
  96. return $doCData ? $this->document->createCDATASection($data) : $this->document->createTextNode((string) $data);
  97. }
  98. public function visitSimpleString($data, array $type, Context $context)
  99. {
  100. if (null === $this->document) {
  101. $this->document = $this->createDocument(null, null, true);
  102. $this->currentNode->appendChild($this->document->createTextNode((string) $data));
  103. return;
  104. }
  105. return $this->document->createTextNode((string) $data);
  106. }
  107. public function visitBoolean($data, array $type, Context $context)
  108. {
  109. if (null === $this->document) {
  110. $this->document = $this->createDocument(null, null, true);
  111. $this->currentNode->appendChild($this->document->createTextNode($data ? 'true' : 'false'));
  112. return;
  113. }
  114. return $this->document->createTextNode($data ? 'true' : 'false');
  115. }
  116. public function visitInteger($data, array $type, Context $context)
  117. {
  118. return $this->visitNumeric($data, $type);
  119. }
  120. public function visitDouble($data, array $type, Context $context)
  121. {
  122. return $this->visitNumeric($data, $type);
  123. }
  124. public function visitArray($data, array $type, Context $context)
  125. {
  126. if (null === $this->document) {
  127. $this->document = $this->createDocument(null, null, true);
  128. }
  129. $entryName = (null !== $this->currentMetadata && null !== $this->currentMetadata->xmlEntryName) ? $this->currentMetadata->xmlEntryName : 'entry';
  130. $keyAttributeName = (null !== $this->currentMetadata && null !== $this->currentMetadata->xmlKeyAttribute) ? $this->currentMetadata->xmlKeyAttribute : null;
  131. foreach ($data as $k => $v) {
  132. $tagName = (null !== $this->currentMetadata && $this->currentMetadata->xmlKeyValuePairs && $this->isElementNameValid($k)) ? $k : $entryName;
  133. $entryNode = $this->document->createElement($tagName);
  134. $this->currentNode->appendChild($entryNode);
  135. $this->setCurrentNode($entryNode);
  136. if (null !== $keyAttributeName) {
  137. $entryNode->setAttribute($keyAttributeName, (string) $k);
  138. }
  139. $typeArray = isset($type['params'][0]) ? (isset($type['params'][1]) && is_array($type['params'][1]) ? $type['params'][1] : $type['params'][0]) : null;
  140. if (null !== $node = $this->navigator->accept($v, $typeArray, $context)) {
  141. $this->currentNode->appendChild($node);
  142. }
  143. $this->revertCurrentNode();
  144. }
  145. }
  146. public function startVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
  147. {
  148. if (null === $this->document) {
  149. $this->document = $this->createDocument(null, null, false);
  150. $this->document->appendChild($this->currentNode = $this->document->createElement($metadata->xmlRootName ?: $this->defaultRootName));
  151. }
  152. $this->addNamespaceAttributes($metadata, $this->currentNode);
  153. $this->hasValue = false;
  154. }
  155. public function visitProperty(PropertyMetadata $metadata, $object, Context $context)
  156. {
  157. $v = $metadata->getValue($object);
  158. if (null === $v && !$context->shouldSerializeNull()) {
  159. return;
  160. }
  161. if ($metadata->xmlAttribute) {
  162. $this->setCurrentMetadata($metadata);
  163. $node = $this->navigator->accept($v, $metadata->type, $context);
  164. $this->revertCurrentMetadata();
  165. if (!$node instanceof \DOMCharacterData) {
  166. throw new RuntimeException(sprintf('Unsupported value for XML attribute. Expected character data, but got %s.', json_encode($v)));
  167. }
  168. $attributeName = $this->namingStrategy->translateName($metadata);
  169. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  170. if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
  171. $prefix = 'ns-'. substr(sha1($namespace), 0, 8);
  172. }
  173. $this->currentNode->setAttributeNS($namespace, $prefix.':'.$attributeName, $node->nodeValue);
  174. } else {
  175. $this->currentNode->setAttribute($attributeName, $node->nodeValue);
  176. }
  177. return;
  178. }
  179. if (($metadata->xmlValue && $this->currentNode->childNodes->length > 0)
  180. || (!$metadata->xmlValue && $this->hasValue)) {
  181. throw new RuntimeException(sprintf('If you make use of @XmlValue, all other properties in the class must have the @XmlAttribute annotation. Invalid usage detected in class %s.', $metadata->class));
  182. }
  183. if ($metadata->xmlValue) {
  184. $this->hasValue = true;
  185. $this->setCurrentMetadata($metadata);
  186. $node = $this->navigator->accept($v, $metadata->type, $context);
  187. $this->revertCurrentMetadata();
  188. if (!$node instanceof \DOMCharacterData) {
  189. throw new RuntimeException(sprintf('Unsupported value for property %s::$%s. Expected character data, but got %s.', $metadata->reflection->class, $metadata->reflection->name, is_object($node) ? get_class($node) : gettype($node)));
  190. }
  191. $this->currentNode->appendChild($node);
  192. return;
  193. }
  194. if ($metadata->xmlAttributeMap) {
  195. if (!is_array($v)) {
  196. throw new RuntimeException(sprintf('Unsupported value type for XML attribute map. Expected array but got %s.', gettype($v)));
  197. }
  198. foreach ($v as $key => $value) {
  199. $this->setCurrentMetadata($metadata);
  200. $node = $this->navigator->accept($value, null, $context);
  201. $this->revertCurrentMetadata();
  202. if (!$node instanceof \DOMCharacterData) {
  203. throw new RuntimeException(sprintf('Unsupported value for a XML attribute map value. Expected character data, but got %s.', json_encode($v)));
  204. }
  205. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  206. if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
  207. $prefix = 'ns-'. substr(sha1($namespace), 0, 8);
  208. }
  209. $this->currentNode->setAttributeNS($namespace, $prefix.':'.$key, $node->nodeValue);
  210. } else {
  211. $this->currentNode->setAttribute($key, $node->nodeValue);
  212. }
  213. }
  214. return;
  215. }
  216. if ($addEnclosingElement = (!$metadata->xmlCollection || !$metadata->xmlCollectionInline) && !$metadata->inline) {
  217. $elementName = $this->namingStrategy->translateName($metadata);
  218. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  219. if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
  220. $prefix = 'ns-'. substr(sha1($namespace), 0, 8);
  221. }
  222. $element = $this->document->createElementNS($namespace, $prefix.':'.$elementName);
  223. } else {
  224. $element = $this->document->createElement($elementName);
  225. }
  226. $this->setCurrentNode($element);
  227. }
  228. $this->setCurrentMetadata($metadata);
  229. if (null !== $node = $this->navigator->accept($v, $metadata->type, $context)) {
  230. $this->currentNode->appendChild($node);
  231. }
  232. $this->revertCurrentMetadata();
  233. if ($addEnclosingElement) {
  234. $this->revertCurrentNode();
  235. if ($element->hasChildNodes() || $element->hasAttributes()
  236. || (isset($metadata->type['name']) && $metadata->type['name'] === 'array' && isset($metadata->type['params'][1]))) {
  237. $this->currentNode->appendChild($element);
  238. }
  239. }
  240. $this->hasValue = false;
  241. }
  242. public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
  243. {
  244. }
  245. public function getResult()
  246. {
  247. return $this->document->saveXML();
  248. }
  249. public function getCurrentNode()
  250. {
  251. return $this->currentNode;
  252. }
  253. public function getCurrentMetadata()
  254. {
  255. return $this->currentMetadata;
  256. }
  257. public function getDocument()
  258. {
  259. return $this->document;
  260. }
  261. public function setCurrentMetadata(PropertyMetadata $metadata)
  262. {
  263. $this->metadataStack->push($this->currentMetadata);
  264. $this->currentMetadata = $metadata;
  265. }
  266. public function setCurrentNode(\DOMNode $node)
  267. {
  268. $this->stack->push($this->currentNode);
  269. $this->currentNode = $node;
  270. }
  271. public function revertCurrentNode()
  272. {
  273. return $this->currentNode = $this->stack->pop();
  274. }
  275. public function revertCurrentMetadata()
  276. {
  277. return $this->currentMetadata = $this->metadataStack->pop();
  278. }
  279. public function createDocument($version = null, $encoding = null, $addRoot = true)
  280. {
  281. $doc = new \DOMDocument($version ?: $this->defaultVersion, $encoding ?: $this->defaultEncoding);
  282. $doc->formatOutput = true;
  283. if ($addRoot) {
  284. $this->setCurrentNode($rootNode = $doc->createElement($this->defaultRootName));
  285. $doc->appendChild($rootNode);
  286. }
  287. return $doc;
  288. }
  289. public function prepare($data)
  290. {
  291. $this->nullWasVisited = false;
  292. return $data;
  293. }
  294. private function visitNumeric($data, array $type)
  295. {
  296. if (null === $this->document) {
  297. $this->document = $this->createDocument(null, null, true);
  298. $this->currentNode->appendChild($textNode = $this->document->createTextNode((string) $data));
  299. return $textNode;
  300. }
  301. return $this->document->createTextNode((string) $data);
  302. }
  303. /**
  304. * Checks that the name is a valid XML element name.
  305. *
  306. * @param string $name
  307. *
  308. * @return boolean
  309. */
  310. private function isElementNameValid($name)
  311. {
  312. return $name && false === strpos($name, ' ') && preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  313. }
  314. private function attachNullNamespace()
  315. {
  316. if (!$this->nullWasVisited) {
  317. $this->document->documentElement->setAttributeNS(
  318. 'http://www.w3.org/2000/xmlns/',
  319. 'xmlns:xsi',
  320. 'http://www.w3.org/2001/XMLSchema-instance'
  321. );
  322. $this->nullWasVisited = true;
  323. }
  324. }
  325. /**
  326. * Adds namespace attributes to the XML root element
  327. *
  328. * @param \JMS\Serializer\Metadata\ClassMetadata $metadata
  329. * @param \DOMElement $element
  330. */
  331. private function addNamespaceAttributes(ClassMetadata $metadata, \DOMElement $element)
  332. {
  333. foreach ($metadata->xmlNamespaces as $prefix => $uri) {
  334. $attribute = 'xmlns';
  335. if ($prefix !== '') {
  336. $attribute .= ':'.$prefix;
  337. }
  338. $element->setAttributeNS('http://www.w3.org/2000/xmlns/', $attribute, $uri);
  339. }
  340. }
  341. }