GraphNavigator.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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\EventDispatcher\ObjectEvent;
  19. use JMS\Serializer\EventDispatcher\PreDeserializeEvent;
  20. use JMS\Serializer\EventDispatcher\PreSerializeEvent;
  21. use JMS\Serializer\Exception\RuntimeException;
  22. use JMS\Serializer\Construction\ObjectConstructorInterface;
  23. use JMS\Serializer\Handler\HandlerRegistryInterface;
  24. use JMS\Serializer\EventDispatcher\EventDispatcherInterface;
  25. use JMS\Serializer\Metadata\ClassMetadata;
  26. use Metadata\MetadataFactoryInterface;
  27. use JMS\Serializer\Exception\InvalidArgumentException;
  28. /**
  29. * Handles traversal along the object graph.
  30. *
  31. * This class handles traversal along the graph, and calls different methods
  32. * on visitors, or custom handlers to process its nodes.
  33. *
  34. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  35. */
  36. final class GraphNavigator
  37. {
  38. const DIRECTION_SERIALIZATION = 1;
  39. const DIRECTION_DESERIALIZATION = 2;
  40. private $dispatcher;
  41. private $metadataFactory;
  42. private $handlerRegistry;
  43. private $objectConstructor;
  44. /**
  45. * Parses a direction string to one of the direction constants.
  46. *
  47. * @param string $dirStr
  48. *
  49. * @return integer
  50. */
  51. public static function parseDirection($dirStr)
  52. {
  53. switch (strtolower($dirStr)) {
  54. case 'serialization':
  55. return self::DIRECTION_SERIALIZATION;
  56. case 'deserialization':
  57. return self::DIRECTION_DESERIALIZATION;
  58. default:
  59. throw new InvalidArgumentException(sprintf('The direction "%s" does not exist.', $dirStr));
  60. }
  61. }
  62. public function __construct(MetadataFactoryInterface $metadataFactory, HandlerRegistryInterface $handlerRegistry, ObjectConstructorInterface $objectConstructor, EventDispatcherInterface $dispatcher = null)
  63. {
  64. $this->dispatcher = $dispatcher;
  65. $this->metadataFactory = $metadataFactory;
  66. $this->handlerRegistry = $handlerRegistry;
  67. $this->objectConstructor = $objectConstructor;
  68. }
  69. /**
  70. * Called for each node of the graph that is being traversed.
  71. *
  72. * @param mixed $data the data depends on the direction, and type of visitor
  73. * @param null|array $type array has the format ["name" => string, "params" => array]
  74. * @param VisitorInterface $visitor
  75. *
  76. * @return mixed the return value depends on the direction, and type of visitor
  77. */
  78. public function accept($data, array $type = null, Context $context)
  79. {
  80. $visitor = $context->getVisitor();
  81. // If the type was not given, we infer the most specific type from the
  82. // input data in serialization mode.
  83. if (null === $type) {
  84. if ($context instanceof DeserializationContext) {
  85. throw new RuntimeException('The type must be given for all properties when deserializing.');
  86. }
  87. $typeName = gettype($data);
  88. if ('object' === $typeName) {
  89. $typeName = get_class($data);
  90. }
  91. $type = array('name' => $typeName, 'params' => array());
  92. }
  93. // If the data is null, we have to force the type to null regardless of the input in order to
  94. // guarantee correct handling of null values, and not have any internal auto-casting behavior.
  95. else if ($context instanceof SerializationContext && null === $data) {
  96. $type = array('name' => 'NULL', 'params' => array());
  97. }
  98. switch ($type['name']) {
  99. case 'NULL':
  100. return $visitor->visitNull($data, $type, $context);
  101. case 'string':
  102. return $visitor->visitString($data, $type, $context);
  103. case 'integer':
  104. return $visitor->visitInteger($data, $type, $context);
  105. case 'boolean':
  106. return $visitor->visitBoolean($data, $type, $context);
  107. case 'double':
  108. case 'float':
  109. return $visitor->visitDouble($data, $type, $context);
  110. case 'array':
  111. return $visitor->visitArray($data, $type, $context);
  112. case 'resource':
  113. $msg = 'Resources are not supported in serialized data.';
  114. if ($context instanceof SerializationContext && null !== $path = $context->getPath()) {
  115. $msg .= ' Path: '.$path;
  116. }
  117. throw new RuntimeException($msg);
  118. default:
  119. // TODO: The rest of this method needs some refactoring.
  120. if ($context instanceof SerializationContext) {
  121. if (null !== $data) {
  122. if ($context->isVisiting($data)) {
  123. return null;
  124. }
  125. $context->startVisiting($data);
  126. }
  127. } elseif ($context instanceof DeserializationContext) {
  128. $context->increaseDepth();
  129. }
  130. // Trigger pre-serialization callbacks, and listeners if they exist.
  131. // Dispatch pre-serialization event before handling data to have ability change type in listener
  132. if ($context instanceof SerializationContext) {
  133. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.pre_serialize', $type['name'], $context->getFormat())) {
  134. $this->dispatcher->dispatch('serializer.pre_serialize', $type['name'], $context->getFormat(), $event = new PreSerializeEvent($context, $data, $type));
  135. $type = $event->getType();
  136. }
  137. } elseif ($context instanceof DeserializationContext) {
  138. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.pre_deserialize', $type['name'], $context->getFormat())) {
  139. $this->dispatcher->dispatch('serializer.pre_deserialize', $type['name'], $context->getFormat(), $event = new PreDeserializeEvent($context, $data, $type));
  140. $type = $event->getType();
  141. $data = $event->getData();
  142. }
  143. }
  144. // First, try whether a custom handler exists for the given type. This is done
  145. // before loading metadata because the type name might not be a class, but
  146. // could also simply be an artifical type.
  147. if (null !== $handler = $this->handlerRegistry->getHandler($context->getDirection(), $type['name'], $context->getFormat())) {
  148. $rs = call_user_func($handler, $visitor, $data, $type, $context);
  149. $this->leaveScope($context, $data);
  150. return $rs;
  151. }
  152. $exclusionStrategy = $context->getExclusionStrategy();
  153. /** @var $metadata ClassMetadata */
  154. $metadata = $this->metadataFactory->getMetadataForClass($type['name']);
  155. if ($context instanceof DeserializationContext && ! empty($metadata->discriminatorMap) && $type['name'] === $metadata->discriminatorBaseClass) {
  156. $metadata = $this->resolveMetadata($context, $data, $metadata);
  157. }
  158. if (null !== $exclusionStrategy && $exclusionStrategy->shouldSkipClass($metadata, $context)) {
  159. $this->leaveScope($context, $data);
  160. return null;
  161. }
  162. $context->pushClassMetadata($metadata);
  163. if ($context instanceof SerializationContext) {
  164. foreach ($metadata->preSerializeMethods as $method) {
  165. $method->invoke($data);
  166. }
  167. }
  168. $object = $data;
  169. if ($context instanceof DeserializationContext) {
  170. $object = $this->objectConstructor->construct($visitor, $metadata, $data, $type);
  171. }
  172. if (isset($metadata->handlerCallbacks[$context->getDirection()][$context->getFormat()])) {
  173. $rs = $object->{$metadata->handlerCallbacks[$context->getDirection()][$context->getFormat()]}(
  174. $visitor,
  175. $context instanceof SerializationContext ? null : $data,
  176. $context
  177. );
  178. $this->afterVisitingObject($metadata, $object, $type, $context);
  179. return $context instanceof SerializationContext ? $rs : $object;
  180. }
  181. $visitor->startVisitingObject($metadata, $object, $type, $context);
  182. foreach ($metadata->propertyMetadata as $propertyMetadata) {
  183. if (null !== $exclusionStrategy && $exclusionStrategy->shouldSkipProperty($propertyMetadata, $context)) {
  184. continue;
  185. }
  186. if ($context instanceof DeserializationContext && $propertyMetadata->readOnly) {
  187. continue;
  188. }
  189. $context->pushPropertyMetadata($propertyMetadata);
  190. $visitor->visitProperty($propertyMetadata, $data, $context);
  191. $context->popPropertyMetadata();
  192. }
  193. if ($context instanceof SerializationContext) {
  194. $this->afterVisitingObject($metadata, $data, $type, $context);
  195. return $visitor->endVisitingObject($metadata, $data, $type, $context);
  196. }
  197. $rs = $visitor->endVisitingObject($metadata, $data, $type, $context);
  198. $this->afterVisitingObject($metadata, $rs, $type, $context);
  199. return $rs;
  200. }
  201. }
  202. private function resolveMetadata(DeserializationContext $context, $data, ClassMetadata $metadata)
  203. {
  204. switch (true) {
  205. case is_array($data) && isset($data[$metadata->discriminatorFieldName]):
  206. $typeValue = (string) $data[$metadata->discriminatorFieldName];
  207. break;
  208. case is_object($data) && isset($data->{$metadata->discriminatorFieldName}):
  209. $typeValue = (string) $data->{$metadata->discriminatorFieldName};
  210. break;
  211. default:
  212. throw new \LogicException(sprintf(
  213. 'The discriminator field name "%s" for base-class "%s" was not found in input data.',
  214. $metadata->discriminatorFieldName,
  215. $metadata->name
  216. ));
  217. }
  218. if ( ! isset($metadata->discriminatorMap[$typeValue])) {
  219. throw new \LogicException(sprintf(
  220. 'The type value "%s" does not exist in the discriminator map of class "%s". Available types: %s',
  221. $typeValue,
  222. $metadata->name,
  223. implode(', ', array_keys($metadata->discriminatorMap))
  224. ));
  225. }
  226. return $this->metadataFactory->getMetadataForClass($metadata->discriminatorMap[$typeValue]);
  227. }
  228. private function leaveScope(Context $context, $data)
  229. {
  230. if ($context instanceof SerializationContext) {
  231. $context->stopVisiting($data);
  232. } elseif ($context instanceof DeserializationContext) {
  233. $context->decreaseDepth();
  234. }
  235. }
  236. private function afterVisitingObject(ClassMetadata $metadata, $object, array $type, Context $context)
  237. {
  238. $this->leaveScope($context, $object);
  239. $context->popClassMetadata();
  240. if ($context instanceof SerializationContext) {
  241. foreach ($metadata->postSerializeMethods as $method) {
  242. $method->invoke($object);
  243. }
  244. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.post_serialize', $metadata->name, $context->getFormat())) {
  245. $this->dispatcher->dispatch('serializer.post_serialize', $metadata->name, $context->getFormat(), new ObjectEvent($context, $object, $type));
  246. }
  247. return;
  248. }
  249. foreach ($metadata->postDeserializeMethods as $method) {
  250. $method->invoke($object);
  251. }
  252. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.post_deserialize', $metadata->name, $context->getFormat())) {
  253. $this->dispatcher->dispatch('serializer.post_deserialize', $metadata->name, $context->getFormat(), new ObjectEvent($context, $object, $type));
  254. }
  255. }
  256. }