XmlDeserializationVisitor.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. /*
  3. * Copyright 2013 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\Serializer;
  18. use JMS\Serializer\Exception\XmlErrorException;
  19. use JMS\Serializer\Exception\LogicException;
  20. use JMS\Serializer\Exception\InvalidArgumentException;
  21. use JMS\Serializer\Exception\RuntimeException;
  22. use JMS\Serializer\Metadata\PropertyMetadata;
  23. use JMS\Serializer\Metadata\ClassMetadata;
  24. class XmlDeserializationVisitor extends AbstractVisitor
  25. {
  26. private $objectStack;
  27. private $metadataStack;
  28. private $currentObject;
  29. private $currentMetadata;
  30. private $result;
  31. private $navigator;
  32. private $disableExternalEntities = true;
  33. private $doctypeWhitelist = array();
  34. public function enableExternalEntities()
  35. {
  36. $this->disableExternalEntities = false;
  37. }
  38. public function setNavigator(GraphNavigator $navigator)
  39. {
  40. $this->navigator = $navigator;
  41. $this->objectStack = new \SplStack;
  42. $this->metadataStack = new \SplStack;
  43. $this->result = null;
  44. }
  45. public function getNavigator()
  46. {
  47. return $this->navigator;
  48. }
  49. public function prepare($data)
  50. {
  51. $previous = libxml_use_internal_errors(true);
  52. $previousEntityLoaderState = libxml_disable_entity_loader($this->disableExternalEntities);
  53. $dom = new \DOMDocument();
  54. $dom->loadXML($data);
  55. foreach ($dom->childNodes as $child) {
  56. if ($child->nodeType === XML_DOCUMENT_TYPE_NODE) {
  57. $internalSubset = str_replace(array("\n", "\r"), '', $child->internalSubset);
  58. if (!in_array($internalSubset, $this->doctypeWhitelist, true)) {
  59. throw new InvalidArgumentException(sprintf(
  60. 'The document type "%s" is not allowed. If it is safe, you may add it to the whitelist configuration.',
  61. $internalSubset
  62. ));
  63. }
  64. }
  65. }
  66. $doc = simplexml_load_string($data);
  67. libxml_use_internal_errors($previous);
  68. libxml_disable_entity_loader($previousEntityLoaderState);
  69. if (false === $doc) {
  70. throw new XmlErrorException(libxml_get_last_error());
  71. }
  72. return $doc;
  73. }
  74. public function visitNull($data, array $type, Context $context)
  75. {
  76. return null;
  77. }
  78. public function visitString($data, array $type, Context $context)
  79. {
  80. $data = (string) $data;
  81. if (null === $this->result) {
  82. $this->result = $data;
  83. }
  84. return $data;
  85. }
  86. public function visitBoolean($data, array $type, Context $context)
  87. {
  88. $data = (string) $data;
  89. if ('true' === $data || '1' === $data) {
  90. $data = true;
  91. } elseif ('false' === $data || '0' === $data) {
  92. $data = false;
  93. } else {
  94. throw new RuntimeException(sprintf('Could not convert data to boolean. Expected "true", or "false", but got %s.', json_encode($data)));
  95. }
  96. if (null === $this->result) {
  97. $this->result = $data;
  98. }
  99. return $data;
  100. }
  101. public function visitInteger($data, array $type, Context $context)
  102. {
  103. $data = (integer) $data;
  104. if (null === $this->result) {
  105. $this->result = $data;
  106. }
  107. return $data;
  108. }
  109. public function visitDouble($data, array $type, Context $context)
  110. {
  111. $data = (double) $data;
  112. if (null === $this->result) {
  113. $this->result = $data;
  114. }
  115. return $data;
  116. }
  117. public function visitArray($data, array $type, Context $context)
  118. {
  119. $entryName = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryName ? $this->currentMetadata->xmlEntryName : 'entry';
  120. if ( ! isset($data->$entryName)) {
  121. if (null === $this->result) {
  122. return $this->result = array();
  123. }
  124. return array();
  125. }
  126. switch (count($type['params'])) {
  127. case 0:
  128. throw new RuntimeException(sprintf('The array type must be specified either as "array<T>", or "array<K,V>".'));
  129. case 1:
  130. $result = array();
  131. if (null === $this->result) {
  132. $this->result = &$result;
  133. }
  134. foreach ($data->$entryName as $v) {
  135. $result[] = $this->navigator->accept($v, $type['params'][0], $context);
  136. }
  137. return $result;
  138. case 2:
  139. if (null === $this->currentMetadata) {
  140. throw new RuntimeException('Maps are not supported on top-level without metadata.');
  141. }
  142. list($keyType, $entryType) = $type['params'];
  143. $result = array();
  144. if (null === $this->result) {
  145. $this->result = &$result;
  146. }
  147. foreach ($data->$entryName as $v) {
  148. if (!isset($v[$this->currentMetadata->xmlKeyAttribute])) {
  149. throw new RuntimeException(sprintf('The key attribute "%s" must be set for each entry of the map.', $this->currentMetadata->xmlKeyAttribute));
  150. }
  151. $k = $this->navigator->accept($v[$this->currentMetadata->xmlKeyAttribute], $keyType, $context);
  152. $result[$k] = $this->navigator->accept($v, $entryType, $context);
  153. }
  154. return $result;
  155. default:
  156. throw new LogicException(sprintf('The array type does not support more than 2 parameters, but got %s.', json_encode($type['params'])));
  157. }
  158. }
  159. public function startVisitingObject(ClassMetadata $metadata, $object, array $type, Context $context)
  160. {
  161. $this->setCurrentObject($object);
  162. if (null === $this->result) {
  163. $this->result = $this->currentObject;
  164. }
  165. }
  166. public function visitProperty(PropertyMetadata $metadata, $data, Context $context)
  167. {
  168. $name = $this->namingStrategy->translateName($metadata);
  169. if (!$metadata->type) {
  170. throw new RuntimeException(sprintf('You must define a type for %s::$%s.', $metadata->reflection->class, $metadata->name));
  171. }
  172. if ($metadata->xmlAttribute) {
  173. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  174. $registeredNamespaces = $data->getDocNamespaces();
  175. if (false === $prefix = array_search($namespace, $registeredNamespaces)) {
  176. $prefix = uniqid('ns-');
  177. $data->registerXPathNamespace ($prefix, $namespace);
  178. }
  179. $attributeName = ($prefix === '')?$name:$prefix.':'.$name;
  180. $nodes = $data->xpath('./@'.$attributeName);
  181. if (!empty($nodes)) {
  182. $v = (string) reset($nodes);
  183. $metadata->reflection->setValue($this->currentObject, $v);
  184. }
  185. } elseif (isset($data[$name])) {
  186. $v = $this->navigator->accept($data[$name], $metadata->type, $context);
  187. $metadata->reflection->setValue($this->currentObject, $v);
  188. }
  189. return;
  190. }
  191. if ($metadata->xmlValue) {
  192. $v = $this->navigator->accept($data, $metadata->type, $context);
  193. $metadata->reflection->setValue($this->currentObject, $v);
  194. return;
  195. }
  196. if ($metadata->xmlCollection) {
  197. $enclosingElem = $data;
  198. if (!$metadata->xmlCollectionInline && isset($data->$name)) {
  199. $enclosingElem = $data->$name;
  200. }
  201. $this->setCurrentMetadata($metadata);
  202. $v = $this->navigator->accept($enclosingElem, $metadata->type, $context);
  203. $this->revertCurrentMetadata();
  204. $metadata->reflection->setValue($this->currentObject, $v);
  205. return;
  206. }
  207. if ('' !== $namespace = (string) $metadata->xmlNamespace) {
  208. $registeredNamespaces = $data->getDocNamespaces();
  209. if (false === $prefix = array_search($namespace, $registeredNamespaces)) {
  210. $prefix = uniqid('ns-');
  211. $data->registerXPathNamespace($prefix, $namespace);
  212. }
  213. $elementName = ($prefix === '')?$name:$prefix.':'.$name;
  214. $nodes = $data->xpath('./'.$elementName );
  215. if (empty($nodes)) {
  216. return;
  217. }
  218. $node = reset($nodes);
  219. } else {
  220. if (!isset($data->$name)) {
  221. return;
  222. }
  223. $node = $data->$name;
  224. }
  225. $v = $this->navigator->accept($node, $metadata->type, $context);
  226. if (null === $metadata->setter) {
  227. $metadata->reflection->setValue($this->currentObject, $v);
  228. return;
  229. }
  230. $this->currentObject->{$metadata->setter}($v);
  231. }
  232. public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
  233. {
  234. $rs = $this->currentObject;
  235. $this->revertCurrentObject();
  236. return $rs;
  237. }
  238. public function setCurrentObject($object)
  239. {
  240. $this->objectStack->push($this->currentObject);
  241. $this->currentObject = $object;
  242. }
  243. public function getCurrentObject()
  244. {
  245. return $this->currentObject;
  246. }
  247. public function revertCurrentObject()
  248. {
  249. return $this->currentObject = $this->objectStack->pop();
  250. }
  251. public function setCurrentMetadata(PropertyMetadata $metadata)
  252. {
  253. $this->metadataStack->push($this->currentMetadata);
  254. $this->currentMetadata = $metadata;
  255. }
  256. public function getCurrentMetadata()
  257. {
  258. return $this->currentMetadata;
  259. }
  260. public function revertCurrentMetadata()
  261. {
  262. return $this->currentMetadata = $this->metadataStack->pop();
  263. }
  264. public function getResult()
  265. {
  266. return $this->result;
  267. }
  268. /**
  269. * @param array<string> $doctypeWhitelist
  270. */
  271. public function setDoctypeWhitelist(array $doctypeWhitelist)
  272. {
  273. $this->doctypeWhitelist = $doctypeWhitelist;
  274. }
  275. /**
  276. * @return array<string>
  277. */
  278. public function getDoctypeWhitelist()
  279. {
  280. return $this->doctypeWhitelist;
  281. }
  282. }