XmlSerializationVisitor.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. if (null !== $node = $this->navigator->accept($v, $this->getElementType($type), $context)) {
  140. $this->currentNode->appendChild($node);
  141. }
  142. $this->revertCurrentNode();
  143. }
  144. }
  145. public function startVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
  146. {
  147. if (null === $this->document) {
  148. $this->document = $this->createDocument(null, null, false);
  149. $this->document->appendChild($this->currentNode = $this->document->createElement($metadata->xmlRootName ?: $this->defaultRootName));
  150. }
  151. $this->addNamespaceAttributes($metadata, $this->currentNode);
  152. $this->hasValue = false;
  153. }
  154. public function visitProperty(PropertyMetadata $metadata, $object, Context $context)
  155. {
  156. $v = $metadata->getValue($object);
  157. if (null === $v && !$context->shouldSerializeNull()) {
  158. return;
  159. }
  160. if ($metadata->xmlAttribute) {
  161. $this->setCurrentMetadata($metadata);
  162. $node = $this->navigator->accept($v, $metadata->type, $context);
  163. $this->revertCurrentMetadata();
  164. if (!$node instanceof \DOMCharacterData) {
  165. throw new RuntimeException(sprintf('Unsupported value for XML attribute. Expected character data, but got %s.', json_encode($v)));
  166. }
  167. $attributeName = $this->namingStrategy->translateName($metadata);
  168. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  169. if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
  170. $prefix = 'ns-'. substr(sha1($namespace), 0, 8);
  171. }
  172. $this->currentNode->setAttributeNS($namespace, $prefix.':'.$attributeName, $node->nodeValue);
  173. } else {
  174. $this->currentNode->setAttribute($attributeName, $node->nodeValue);
  175. }
  176. return;
  177. }
  178. if (($metadata->xmlValue && $this->currentNode->childNodes->length > 0)
  179. || (!$metadata->xmlValue && $this->hasValue)) {
  180. 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));
  181. }
  182. if ($metadata->xmlValue) {
  183. $this->hasValue = true;
  184. $this->setCurrentMetadata($metadata);
  185. $node = $this->navigator->accept($v, $metadata->type, $context);
  186. $this->revertCurrentMetadata();
  187. if (!$node instanceof \DOMCharacterData) {
  188. 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)));
  189. }
  190. $this->currentNode->appendChild($node);
  191. return;
  192. }
  193. if ($metadata->xmlAttributeMap) {
  194. if (!is_array($v)) {
  195. throw new RuntimeException(sprintf('Unsupported value type for XML attribute map. Expected array but got %s.', gettype($v)));
  196. }
  197. foreach ($v as $key => $value) {
  198. $this->setCurrentMetadata($metadata);
  199. $node = $this->navigator->accept($value, null, $context);
  200. $this->revertCurrentMetadata();
  201. if (!$node instanceof \DOMCharacterData) {
  202. throw new RuntimeException(sprintf('Unsupported value for a XML attribute map value. Expected character data, but got %s.', json_encode($v)));
  203. }
  204. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  205. if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
  206. $prefix = 'ns-'. substr(sha1($namespace), 0, 8);
  207. }
  208. $this->currentNode->setAttributeNS($namespace, $prefix.':'.$key, $node->nodeValue);
  209. } else {
  210. $this->currentNode->setAttribute($key, $node->nodeValue);
  211. }
  212. }
  213. return;
  214. }
  215. if ($addEnclosingElement = (!$metadata->xmlCollection || !$metadata->xmlCollectionInline) && !$metadata->inline) {
  216. $elementName = $this->namingStrategy->translateName($metadata);
  217. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  218. if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
  219. $prefix = 'ns-'. substr(sha1($namespace), 0, 8);
  220. }
  221. $element = $this->document->createElementNS($namespace, $prefix.':'.$elementName);
  222. } else {
  223. $element = $this->document->createElement($elementName);
  224. }
  225. $this->setCurrentNode($element);
  226. }
  227. $this->setCurrentMetadata($metadata);
  228. if (null !== $node = $this->navigator->accept($v, $metadata->type, $context)) {
  229. $this->currentNode->appendChild($node);
  230. }
  231. $this->revertCurrentMetadata();
  232. if ($addEnclosingElement) {
  233. $this->revertCurrentNode();
  234. if ($element->hasChildNodes() || $element->hasAttributes()
  235. || (isset($metadata->type['name']) && $metadata->type['name'] === 'array' && isset($metadata->type['params'][1]))) {
  236. $this->currentNode->appendChild($element);
  237. }
  238. }
  239. $this->hasValue = false;
  240. }
  241. public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
  242. {
  243. }
  244. public function getResult()
  245. {
  246. return $this->document->saveXML();
  247. }
  248. public function getCurrentNode()
  249. {
  250. return $this->currentNode;
  251. }
  252. public function getCurrentMetadata()
  253. {
  254. return $this->currentMetadata;
  255. }
  256. public function getDocument()
  257. {
  258. return $this->document;
  259. }
  260. public function setCurrentMetadata(PropertyMetadata $metadata)
  261. {
  262. $this->metadataStack->push($this->currentMetadata);
  263. $this->currentMetadata = $metadata;
  264. }
  265. public function setCurrentNode(\DOMNode $node)
  266. {
  267. $this->stack->push($this->currentNode);
  268. $this->currentNode = $node;
  269. }
  270. public function revertCurrentNode()
  271. {
  272. return $this->currentNode = $this->stack->pop();
  273. }
  274. public function revertCurrentMetadata()
  275. {
  276. return $this->currentMetadata = $this->metadataStack->pop();
  277. }
  278. public function createDocument($version = null, $encoding = null, $addRoot = true)
  279. {
  280. $doc = new \DOMDocument($version ?: $this->defaultVersion, $encoding ?: $this->defaultEncoding);
  281. $doc->formatOutput = true;
  282. if ($addRoot) {
  283. $this->setCurrentNode($rootNode = $doc->createElement($this->defaultRootName));
  284. $doc->appendChild($rootNode);
  285. }
  286. return $doc;
  287. }
  288. public function prepare($data)
  289. {
  290. $this->nullWasVisited = false;
  291. return $data;
  292. }
  293. private function visitNumeric($data, array $type)
  294. {
  295. if (null === $this->document) {
  296. $this->document = $this->createDocument(null, null, true);
  297. $this->currentNode->appendChild($textNode = $this->document->createTextNode((string) $data));
  298. return $textNode;
  299. }
  300. return $this->document->createTextNode((string) $data);
  301. }
  302. /**
  303. * Checks that the name is a valid XML element name.
  304. *
  305. * @param string $name
  306. *
  307. * @return boolean
  308. */
  309. private function isElementNameValid($name)
  310. {
  311. return $name && false === strpos($name, ' ') && preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  312. }
  313. private function attachNullNamespace()
  314. {
  315. if (!$this->nullWasVisited) {
  316. $this->document->documentElement->setAttributeNS(
  317. 'http://www.w3.org/2000/xmlns/',
  318. 'xmlns:xsi',
  319. 'http://www.w3.org/2001/XMLSchema-instance'
  320. );
  321. $this->nullWasVisited = true;
  322. }
  323. }
  324. /**
  325. * Adds namespace attributes to the XML root element
  326. *
  327. * @param \JMS\Serializer\Metadata\ClassMetadata $metadata
  328. * @param \DOMElement $element
  329. */
  330. private function addNamespaceAttributes(ClassMetadata $metadata, \DOMElement $element)
  331. {
  332. foreach ($metadata->xmlNamespaces as $prefix => $uri) {
  333. $attribute = 'xmlns';
  334. if ($prefix !== '') {
  335. $attribute .= ':'.$prefix;
  336. }
  337. $element->setAttributeNS('http://www.w3.org/2000/xmlns/', $attribute, $uri);
  338. }
  339. }
  340. }