XmlSerializationVisitor.php 10 KB

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