XmlSerializationVisitor.php 10 KB

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