XmlSerializationVisitor.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php
  2. /*
  3. * Copyright 2011 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\SerializerBundle\Serializer;
  18. use JMS\SerializerBundle\Exception\RuntimeException;
  19. use JMS\SerializerBundle\Metadata\ClassMetadata;
  20. use JMS\SerializerBundle\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. public function setDefaultRootName($name)
  39. {
  40. $this->defaultRootName = $name;
  41. }
  42. public function setDefaultVersion($version)
  43. {
  44. $this->defaultVersion = $version;
  45. }
  46. public function setDefaultEncoding($encoding)
  47. {
  48. $this->defaultEncoding = $encoding;
  49. }
  50. public function setNavigator(GraphNavigator $navigator)
  51. {
  52. $this->navigator = $navigator;
  53. $this->document = null;
  54. $this->stack = new \SplStack;
  55. $this->metadataStack = new \SplStack;
  56. }
  57. public function getNavigator()
  58. {
  59. return $this->navigator;
  60. }
  61. public function visitNull($data, array $type)
  62. {
  63. if (null === $this->document) {
  64. $this->document = $this->createDocument(null, null, true);
  65. $node = $this->document->createAttribute('xsi:nil');
  66. $node->value = 'true';
  67. $this->currentNode->appendChild($node);
  68. return;
  69. }
  70. $node = $this->document->createAttribute('xsi:nil');
  71. $node->value = 'true';
  72. return $node;
  73. }
  74. public function visitString($data, array $type)
  75. {
  76. if (null === $this->document) {
  77. $this->document = $this->createDocument(null, null, true);
  78. $this->currentNode->appendChild($this->document->createCDATASection($data));
  79. return;
  80. }
  81. return $this->document->createCDATASection($data);
  82. }
  83. public function visitBoolean($data, array $type)
  84. {
  85. if (null === $this->document) {
  86. $this->document = $this->createDocument(null, null, true);
  87. $this->currentNode->appendChild($this->document->createTextNode($data ? 'true' : 'false'));
  88. return;
  89. }
  90. return $this->document->createTextNode($data ? 'true' : 'false');
  91. }
  92. public function visitInteger($data, array $type)
  93. {
  94. return $this->visitNumeric($data, $type);
  95. }
  96. public function visitDouble($data, array $type)
  97. {
  98. return $this->visitNumeric($data, $type);
  99. }
  100. public function visitArray($data, array $type)
  101. {
  102. if (null === $this->document) {
  103. $this->document = $this->createDocument(null, null, true);
  104. }
  105. $entryName = (null !== $this->currentMetadata && null !== $this->currentMetadata->xmlEntryName) ? $this->currentMetadata->xmlEntryName : 'entry';
  106. $keyAttributeName = (null !== $this->currentMetadata && null !== $this->currentMetadata->xmlKeyAttribute) ? $this->currentMetadata->xmlKeyAttribute : null;
  107. foreach ($data as $k => $v) {
  108. $tagName = (null !== $this->currentMetadata && $this->currentMetadata->xmlKeyValuePairs && $this->isElementNameValid($k)) ? $k : $entryName;
  109. $entryNode = $this->document->createElement($tagName);
  110. $this->currentNode->appendChild($entryNode);
  111. $this->setCurrentNode($entryNode);
  112. if (null !== $keyAttributeName) {
  113. $entryNode->setAttribute($keyAttributeName, (string) $k);
  114. }
  115. if (null !== $node = $this->navigator->accept($v, isset($type['params'][1]) ? $type['params'][1] : null, $this)) {
  116. $this->currentNode->appendChild($node);
  117. }
  118. $this->revertCurrentNode();
  119. }
  120. }
  121. public function startVisitingObject(ClassMetadata $metadata, $data, array $type)
  122. {
  123. if (null === $this->document) {
  124. $this->document = $this->createDocument(null, null, false);
  125. $this->document->appendChild($this->currentNode = $this->document->createElement($metadata->xmlRootName ?: $this->defaultRootName));
  126. }
  127. $this->hasValue = false;
  128. }
  129. public function visitProperty(PropertyMetadata $metadata, $object)
  130. {
  131. $v = (null === $metadata->getter ? $metadata->reflection->getValue($object)
  132. : $object->{$metadata->getter}());
  133. if (null === $v && !$this->shouldSerializeNull()) {
  134. return;
  135. }
  136. if ($metadata->xmlAttribute) {
  137. $node = $this->navigator->accept($v, $metadata->type, $this);
  138. if (!$node instanceof \DOMCharacterData) {
  139. throw new RuntimeException(sprintf('Unsupported value for XML attribute. Expected character data, but got %s.', json_encode($v)));
  140. }
  141. $this->currentNode->setAttribute($this->namingStrategy->translateName($metadata), $node->nodeValue);
  142. return;
  143. }
  144. if (($metadata->xmlValue && $this->currentNode->childNodes->length > 0)
  145. || (!$metadata->xmlValue && $this->hasValue)) {
  146. 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));
  147. }
  148. if ($metadata->xmlValue) {
  149. $this->hasValue = true;
  150. $node = $this->navigator->accept($v, $metadata->type, $this);
  151. if (!$node instanceof \DOMCharacterData) {
  152. 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)));
  153. }
  154. $this->currentNode->appendChild($node);
  155. return;
  156. }
  157. if ($metadata->xmlAttributeMap) {
  158. if (!is_array($v)) {
  159. throw new RuntimeException(sprintf('Unsupported value type for XML attribute map. Expected array but got %s.', gettype($v)));
  160. }
  161. foreach ($v as $key => $value) {
  162. $node = $this->navigator->accept($value, null, $this);
  163. if (!$node instanceof \DOMCharacterData) {
  164. throw new RuntimeException(sprintf('Unsupported value for a XML attribute map value. Expected character data, but got %s.', json_encode($v)));
  165. }
  166. $this->currentNode->setAttribute($key, $node->nodeValue);
  167. }
  168. return;
  169. }
  170. if ($addEnclosingElement = (!$metadata->xmlCollection || !$metadata->xmlCollectionInline) && !$metadata->inline) {
  171. $element = $this->document->createElement($this->namingStrategy->translateName($metadata));
  172. $this->setCurrentNode($element);
  173. }
  174. $this->setCurrentMetadata($metadata);
  175. if (null !== $node = $this->navigator->accept($v, $metadata->type, $this)) {
  176. $this->currentNode->appendChild($node);
  177. }
  178. $this->revertCurrentMetadata();
  179. if ($addEnclosingElement) {
  180. $this->revertCurrentNode();
  181. if ($element->hasChildNodes() || $element->hasAttributes()
  182. || (isset($metadata->type['name']) && $metadata->type['name'] === 'array' && isset($metadata->type['params'][1]))) {
  183. $this->currentNode->appendChild($element);
  184. }
  185. }
  186. $this->hasValue = false;
  187. }
  188. public function endVisitingObject(ClassMetadata $metadata, $data, array $type)
  189. {
  190. }
  191. public function getResult()
  192. {
  193. return $this->document->saveXML();
  194. }
  195. public function getCurrentNode()
  196. {
  197. return $this->currentNode;
  198. }
  199. public function getCurrentMetadata()
  200. {
  201. return $this->currentMetadata;
  202. }
  203. public function getDocument()
  204. {
  205. return $this->document;
  206. }
  207. public function setCurrentMetadata(PropertyMetadata $metadata)
  208. {
  209. $this->metadataStack->push($this->currentMetadata);
  210. $this->currentMetadata = $metadata;
  211. }
  212. public function setCurrentNode(\DOMNode $node)
  213. {
  214. $this->stack->push($this->currentNode);
  215. $this->currentNode = $node;
  216. }
  217. public function revertCurrentNode()
  218. {
  219. return $this->currentNode = $this->stack->pop();
  220. }
  221. public function revertCurrentMetadata()
  222. {
  223. return $this->currentMetadata = $this->metadataStack->pop();
  224. }
  225. public function createDocument($version = null, $encoding = null, $addRoot = true)
  226. {
  227. $doc = new \DOMDocument($version ?: $this->defaultVersion, $encoding ?: $this->defaultEncoding);
  228. $doc->formatOutput = true;
  229. if ($addRoot) {
  230. $this->setCurrentNode($rootNode = $doc->createElement($this->defaultRootName));
  231. $doc->appendChild($rootNode);
  232. }
  233. return $doc;
  234. }
  235. private function visitNumeric($data, array $type)
  236. {
  237. if (null === $this->document) {
  238. $this->document = $this->createDocument(null, null, true);
  239. $this->currentNode->appendChild($textNode = $this->document->createTextNode((string) $data));
  240. return $textNode;
  241. }
  242. return $this->document->createTextNode((string) $data);
  243. }
  244. /**
  245. * Checks that the name is a valid XML element name.
  246. *
  247. * @param string $name
  248. *
  249. * @return boolean
  250. */
  251. private function isElementNameValid($name)
  252. {
  253. return $name && false === strpos($name, ' ') && preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  254. }
  255. }