GraphNavigator.php 11 KB

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