XmlSerializationVisitor.php 9.5 KB

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