XmlSerializationVisitor.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 visitArray($data, $type)
  89. {
  90. if (null === $this->document) {
  91. $this->document = $this->createDocument(null, null, true);
  92. }
  93. $entryName = (null !== $this->currentMetadata && null !== $this->currentMetadata->xmlEntryName) ? $this->currentMetadata->xmlEntryName : 'entry';
  94. $keyAttributeName = (null !== $this->currentMetadata && null !== $this->currentMetadata->xmlKeyAttribute) ? $this->currentMetadata->xmlKeyAttribute : null;
  95. foreach ($data as $k => $v) {
  96. $tagName = (null !== $this->currentMetadata && $this->currentMetadata->xmlKeyValuePairs && $this->isElementNameValid($k)) ? $k : $entryName;
  97. $entryNode = $this->document->createElement($tagName);
  98. $this->currentNode->appendChild($entryNode);
  99. $this->setCurrentNode($entryNode);
  100. if (null !== $keyAttributeName) {
  101. $entryNode->setAttribute($keyAttributeName, (string) $k);
  102. }
  103. if (null !== $node = $this->navigator->accept($v, null, $this)) {
  104. $this->currentNode->appendChild($node);
  105. }
  106. $this->revertCurrentNode();
  107. }
  108. }
  109. public function visitTraversable($data, $type)
  110. {
  111. return $this->visitArray($data, $type);
  112. }
  113. public function startVisitingObject(ClassMetadata $metadata, $data, $type)
  114. {
  115. if (null === $this->document) {
  116. $this->document = $this->createDocument(null, null, false);
  117. $this->document->appendChild($this->currentNode = $this->document->createElement($metadata->xmlRootName ?: $this->defaultRootName));
  118. }
  119. $this->hasValue = false;
  120. }
  121. public function visitProperty(PropertyMetadata $metadata, $object)
  122. {
  123. $v = (null === $metadata->getter ? $metadata->reflection->getValue($object)
  124. : $object->{$metadata->getter}());
  125. if (null === $v) {
  126. return;
  127. }
  128. if ($metadata->xmlAttribute) {
  129. $node = $this->navigator->accept($v, null, $this);
  130. if (!$node instanceof \DOMCharacterData) {
  131. throw new RuntimeException(sprintf('Unsupported value for XML attribute. Expected character data, but got %s.', json_encode($v)));
  132. }
  133. $this->currentNode->setAttribute($this->namingStrategy->translateName($metadata), $node->nodeValue);
  134. return;
  135. }
  136. if (($metadata->xmlValue && $this->currentNode->childNodes->length > 0)
  137. || (!$metadata->xmlValue && $this->hasValue)) {
  138. 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));
  139. }
  140. if ($metadata->xmlValue) {
  141. $this->hasValue = true;
  142. $node = $this->navigator->accept($v, null, $this);
  143. if (!$node instanceof \DOMCharacterData) {
  144. 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)));
  145. }
  146. $this->currentNode->appendChild($node);
  147. return;
  148. }
  149. if ($addEnclosingElement = (!$metadata->xmlCollection || !$metadata->xmlCollectionInline) && !$metadata->inline) {
  150. $element = $this->document->createElement($this->namingStrategy->translateName($metadata));
  151. $this->setCurrentNode($element);
  152. }
  153. $this->setCurrentMetadata($metadata);
  154. if (null !== $node = $this->navigator->accept($v, null, $this)) {
  155. $this->currentNode->appendChild($node);
  156. }
  157. $this->revertCurrentMetadata();
  158. if ($addEnclosingElement) {
  159. $this->revertCurrentNode();
  160. if ($element->hasChildNodes() || $element->hasAttributes()) {
  161. $this->currentNode->appendChild($element);
  162. }
  163. }
  164. $this->hasValue = false;
  165. }
  166. public function endVisitingObject(ClassMetadata $metadata, $data, $type)
  167. {
  168. }
  169. public function visitPropertyUsingCustomHandler(PropertyMetadata $metadata, $object)
  170. {
  171. // TODO
  172. return false;
  173. }
  174. public function getResult()
  175. {
  176. return $this->document->saveXML();
  177. }
  178. public function getCurrentNode()
  179. {
  180. return $this->currentNode;
  181. }
  182. public function getCurrentMetadata()
  183. {
  184. return $this->currentMetadata;
  185. }
  186. public function getDocument()
  187. {
  188. return $this->document;
  189. }
  190. public function setCurrentMetadata(PropertyMetadata $metadata)
  191. {
  192. $this->metadataStack->push($this->currentMetadata);
  193. $this->currentMetadata = $metadata;
  194. }
  195. public function setCurrentNode(\DOMNode $node)
  196. {
  197. $this->stack->push($this->currentNode);
  198. $this->currentNode = $node;
  199. }
  200. public function revertCurrentNode()
  201. {
  202. return $this->currentNode = $this->stack->pop();
  203. }
  204. public function revertCurrentMetadata()
  205. {
  206. return $this->currentMetadata = $this->metadataStack->pop();
  207. }
  208. public function createDocument($version = null, $encoding = null, $addRoot = true)
  209. {
  210. $doc = new \DOMDocument($version ?: $this->defaultVersion, $encoding ?: $this->defaultEncoding);
  211. $doc->formatOutput = true;
  212. if ($addRoot) {
  213. $this->setCurrentNode($rootNode = $doc->createElement($this->defaultRootName));
  214. $doc->appendChild($rootNode);
  215. }
  216. return $doc;
  217. }
  218. private function visitNumeric($data, $type)
  219. {
  220. if (null === $this->document) {
  221. $this->document = $this->createDocument(null, null, true);
  222. $this->currentNode->appendChild($textNode = $this->document->createTextNode((string) $data));
  223. return $textNode;
  224. }
  225. return $this->document->createTextNode((string) $data);
  226. }
  227. /**
  228. * Checks the name is a valid xml element name
  229. *
  230. * @param string $name
  231. *
  232. * @return Boolean
  233. */
  234. private function isElementNameValid($name)
  235. {
  236. return $name &&
  237. false === strpos($name, ' ') &&
  238. preg_match('#^[\pL_][\pL0-9._-]*$#ui', $name);
  239. }
  240. }