GraphNavigator.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. *
  75. * @return mixed the return value depends on the direction, and type of visitor
  76. */
  77. public function accept($data, array $type = null, Context $context)
  78. {
  79. $visitor = $context->getVisitor();
  80. // If the type was not given, we infer the most specific type from the
  81. // input data in serialization mode.
  82. if (null === $type) {
  83. if ($context instanceof DeserializationContext) {
  84. throw new RuntimeException('The type must be given for all properties when deserializing.');
  85. }
  86. $typeName = gettype($data);
  87. if ('object' === $typeName) {
  88. $typeName = get_class($data);
  89. }
  90. $type = array('name' => $typeName, 'params' => array());
  91. }
  92. // If the data is null, we have to force the type to null regardless of the input in order to
  93. // guarantee correct handling of null values, and not have any internal auto-casting behavior.
  94. else if ($context instanceof SerializationContext && null === $data) {
  95. $type = array('name' => 'NULL', 'params' => array());
  96. }
  97. switch ($type['name']) {
  98. case 'NULL':
  99. return $visitor->visitNull($data, $type, $context);
  100. case 'string':
  101. return $visitor->visitString($data, $type, $context);
  102. case 'integer':
  103. return $visitor->visitInteger($data, $type, $context);
  104. case 'boolean':
  105. return $visitor->visitBoolean($data, $type, $context);
  106. case 'double':
  107. case 'float':
  108. return $visitor->visitDouble($data, $type, $context);
  109. case 'array':
  110. return $visitor->visitArray($data, $type, $context);
  111. case 'resource':
  112. $msg = 'Resources are not supported in serialized data.';
  113. if ($context instanceof SerializationContext && null !== $path = $context->getPath()) {
  114. $msg .= ' Path: '.$path;
  115. }
  116. throw new RuntimeException($msg);
  117. default:
  118. // TODO: The rest of this method needs some refactoring.
  119. if ($context instanceof SerializationContext) {
  120. if (null !== $data) {
  121. if ($context->isVisiting($data)) {
  122. return null;
  123. }
  124. $context->startVisiting($data);
  125. }
  126. // If we're serializing a polymorphic type, then we'll be interested in the
  127. // metadata for the actual type of the object, not the base class.
  128. if (class_exists($type['name'], false) || interface_exists($type['name'], false)) {
  129. if (is_subclass_of($data, $type['name'], false)) {
  130. $type = array('name' => get_class($data), 'params' => array());
  131. }
  132. }
  133. } elseif ($context instanceof DeserializationContext) {
  134. $context->increaseDepth();
  135. }
  136. // Trigger pre-serialization callbacks, and listeners if they exist.
  137. // Dispatch pre-serialization event before handling data to have ability change type in listener
  138. if ($context instanceof SerializationContext) {
  139. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.pre_serialize', $type['name'], $context->getFormat())) {
  140. $this->dispatcher->dispatch('serializer.pre_serialize', $type['name'], $context->getFormat(), $event = new PreSerializeEvent($context, $data, $type));
  141. $type = $event->getType();
  142. }
  143. } elseif ($context instanceof DeserializationContext) {
  144. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.pre_deserialize', $type['name'], $context->getFormat())) {
  145. $this->dispatcher->dispatch('serializer.pre_deserialize', $type['name'], $context->getFormat(), $event = new PreDeserializeEvent($context, $data, $type));
  146. $type = $event->getType();
  147. $data = $event->getData();
  148. }
  149. }
  150. // First, try whether a custom handler exists for the given type. This is done
  151. // before loading metadata because the type name might not be a class, but
  152. // could also simply be an artifical type.
  153. if (null !== $handler = $this->handlerRegistry->getHandler($context->getDirection(), $type['name'], $context->getFormat())) {
  154. $rs = call_user_func($handler, $visitor, $data, $type, $context);
  155. $this->leaveScope($context, $data);
  156. return $rs;
  157. }
  158. $exclusionStrategy = $context->getExclusionStrategy();
  159. /** @var $metadata ClassMetadata */
  160. $metadata = $this->metadataFactory->getMetadataForClass($type['name']);
  161. if ($context instanceof DeserializationContext && ! empty($metadata->discriminatorMap) && $type['name'] === $metadata->discriminatorBaseClass) {
  162. $metadata = $this->resolveMetadata($context, $data, $metadata);
  163. }
  164. if (null !== $exclusionStrategy && $exclusionStrategy->shouldSkipClass($metadata, $context)) {
  165. $this->leaveScope($context, $data);
  166. return null;
  167. }
  168. $context->pushClassMetadata($metadata);
  169. if ($context instanceof SerializationContext) {
  170. foreach ($metadata->preSerializeMethods as $method) {
  171. $method->invoke($data);
  172. }
  173. }
  174. $object = $data;
  175. if ($context instanceof DeserializationContext) {
  176. $object = $this->objectConstructor->construct($visitor, $metadata, $data, $type, $context);
  177. }
  178. if (isset($metadata->handlerCallbacks[$context->getDirection()][$context->getFormat()])) {
  179. $rs = $object->{$metadata->handlerCallbacks[$context->getDirection()][$context->getFormat()]}(
  180. $visitor,
  181. $context instanceof SerializationContext ? null : $data,
  182. $context
  183. );
  184. $this->afterVisitingObject($metadata, $object, $type, $context);
  185. return $context instanceof SerializationContext ? $rs : $object;
  186. }
  187. $visitor->startVisitingObject($metadata, $object, $type, $context);
  188. foreach ($metadata->propertyMetadata as $propertyMetadata) {
  189. if (null !== $exclusionStrategy && $exclusionStrategy->shouldSkipProperty($propertyMetadata, $context)) {
  190. continue;
  191. }
  192. if ($context instanceof DeserializationContext && $propertyMetadata->readOnly) {
  193. continue;
  194. }
  195. $context->pushPropertyMetadata($propertyMetadata);
  196. $visitor->visitProperty($propertyMetadata, $data, $context);
  197. $context->popPropertyMetadata();
  198. }
  199. if ($context instanceof SerializationContext) {
  200. $this->afterVisitingObject($metadata, $data, $type, $context);
  201. return $visitor->endVisitingObject($metadata, $data, $type, $context);
  202. }
  203. $rs = $visitor->endVisitingObject($metadata, $data, $type, $context);
  204. $this->afterVisitingObject($metadata, $rs, $type, $context);
  205. return $rs;
  206. }
  207. }
  208. private function resolveMetadata(DeserializationContext $context, $data, ClassMetadata $metadata)
  209. {
  210. switch (true) {
  211. case is_array($data) && isset($data[$metadata->discriminatorFieldName]):
  212. $typeValue = (string) $data[$metadata->discriminatorFieldName];
  213. break;
  214. case is_object($data) && isset($data->{$metadata->discriminatorFieldName}):
  215. $typeValue = (string) $data->{$metadata->discriminatorFieldName};
  216. break;
  217. default:
  218. throw new \LogicException(sprintf(
  219. 'The discriminator field name "%s" for base-class "%s" was not found in input data.',
  220. $metadata->discriminatorFieldName,
  221. $metadata->name
  222. ));
  223. }
  224. if ( ! isset($metadata->discriminatorMap[$typeValue])) {
  225. throw new \LogicException(sprintf(
  226. 'The type value "%s" does not exist in the discriminator map of class "%s". Available types: %s',
  227. $typeValue,
  228. $metadata->name,
  229. implode(', ', array_keys($metadata->discriminatorMap))
  230. ));
  231. }
  232. return $this->metadataFactory->getMetadataForClass($metadata->discriminatorMap[$typeValue]);
  233. }
  234. private function leaveScope(Context $context, $data)
  235. {
  236. if ($context instanceof SerializationContext) {
  237. $context->stopVisiting($data);
  238. } elseif ($context instanceof DeserializationContext) {
  239. $context->decreaseDepth();
  240. }
  241. }
  242. private function afterVisitingObject(ClassMetadata $metadata, $object, array $type, Context $context)
  243. {
  244. $this->leaveScope($context, $object);
  245. $context->popClassMetadata();
  246. if ($context instanceof SerializationContext) {
  247. foreach ($metadata->postSerializeMethods as $method) {
  248. $method->invoke($object);
  249. }
  250. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.post_serialize', $metadata->name, $context->getFormat())) {
  251. $this->dispatcher->dispatch('serializer.post_serialize', $metadata->name, $context->getFormat(), new ObjectEvent($context, $object, $type));
  252. }
  253. return;
  254. }
  255. foreach ($metadata->postDeserializeMethods as $method) {
  256. $method->invoke($object);
  257. }
  258. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.post_deserialize', $metadata->name, $context->getFormat())) {
  259. $this->dispatcher->dispatch('serializer.post_deserialize', $metadata->name, $context->getFormat(), new ObjectEvent($context, $object, $type));
  260. }
  261. }
  262. }