XmlSerializationVisitor.php 9.0 KB

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