GraphNavigator.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 array|null $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. switch ($type['name']) {
  105. case 'NULL':
  106. return $visitor->visitNull($data, $type);
  107. case 'string':
  108. return $visitor->visitString($data, $type);
  109. case 'integer':
  110. return $visitor->visitInteger($data, $type);
  111. case 'boolean':
  112. return $visitor->visitBoolean($data, $type);
  113. case 'double':
  114. return $visitor->visitDouble($data, $type);
  115. case 'array':
  116. return $visitor->visitArray($data, $type);
  117. case 'resource':
  118. $msg = 'Resources are not supported in serialized data.';
  119. if (null !== $path = $this->getCurrentPath()) {
  120. $msg .= ' Path: '.implode(' -> ', $path);
  121. }
  122. throw new \RuntimeException($msg);
  123. default:
  124. $isSerializing = self::DIRECTION_SERIALIZATION === $this->direction;
  125. if ($isSerializing && null !== $data) {
  126. if ($this->visiting->contains($data)) {
  127. return null;
  128. }
  129. $this->visiting->attach($data);
  130. }
  131. // First, try whether a custom handler exists for the given type. This is done
  132. // before loading metadata because the type name might not be a class, but
  133. // could also simply be an artifical type.
  134. if (null !== $handler = $this->handlerRegistry->getHandler($this->direction, $type['name'], $this->format)) {
  135. $rs = call_user_func($handler, $visitor, $data, $type);
  136. if ($isSerializing) {
  137. $this->visiting->detach($data);
  138. }
  139. return $rs;
  140. }
  141. // Trigger pre-serialization callbacks, and listeners if they exist.
  142. if ($isSerializing) {
  143. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.pre_serialize', $type['name'], $this->format)) {
  144. $this->dispatcher->dispatch('serializer.pre_serialize', $type['name'], $this->format, $event = new PreSerializeEvent($visitor, $data, $type));
  145. $type = $event->getType();
  146. }
  147. }
  148. // Load metadata, and check whether this class should be excluded.
  149. $metadata = $this->metadataFactory->getMetadataForClass($type['name']);
  150. if (null !== $this->exclusionStrategy && $this->exclusionStrategy->shouldSkipClass($metadata, $isSerializing ? $data : null)) {
  151. if ($isSerializing) {
  152. $this->visiting->detach($data);
  153. }
  154. return null;
  155. }
  156. if ($isSerializing) {
  157. foreach ($metadata->preSerializeMethods as $method) {
  158. $method->invoke($data);
  159. }
  160. }
  161. $object = $data;
  162. if ( ! $isSerializing) {
  163. $object = $this->objectConstructor->construct($visitor, $metadata, $data, $type);
  164. }
  165. if (isset($metadata->handlerCallbacks[$this->direction][$this->format])) {
  166. $rs = $object->{$metadata->handlerCallbacks[$this->direction][$this->format]}($visitor, $isSerializing ? null : $data);
  167. $this->afterVisitingObject($visitor, $metadata, $object, $type);
  168. return $isSerializing ? $rs : $object;
  169. }
  170. $visitor->startVisitingObject($metadata, $object, $type);
  171. foreach ($metadata->propertyMetadata as $propertyMetadata) {
  172. if (null !== $this->exclusionStrategy && $this->exclusionStrategy->shouldSkipProperty($propertyMetadata, $isSerializing ? $data : null)) {
  173. continue;
  174. }
  175. if ( ! $isSerializing && $propertyMetadata->readOnly) {
  176. continue;
  177. }
  178. $visitor->visitProperty($propertyMetadata, $data);
  179. }
  180. if ($isSerializing) {
  181. $this->afterVisitingObject($visitor, $metadata, $data, $type);
  182. return $visitor->endVisitingObject($metadata, $data, $type);
  183. }
  184. $rs = $visitor->endVisitingObject($metadata, $data, $type);
  185. $this->afterVisitingObject($visitor, $metadata, $rs, $type);
  186. return $rs;
  187. }
  188. }
  189. /**
  190. * Detaches an object from the visiting map.
  191. *
  192. * Use this method if you like to re-visit an object which is already
  193. * being visited. Be aware that you might cause an endless loop if you
  194. * use this inappropriately.
  195. *
  196. * @param object $object
  197. */
  198. public function detachObject($object)
  199. {
  200. if (null === $object) {
  201. throw new InvalidArgumentException('$object cannot be null');
  202. } else if (!is_object($object)) {
  203. throw new InvalidArgumentException(sprintf('Expected an object to detach, given "%s".', gettype($object)));
  204. }
  205. $this->visiting->detach($object);
  206. }
  207. private function getCurrentPath()
  208. {
  209. $path = array();
  210. foreach ($this->visiting as $obj) {
  211. $path[] = get_class($obj);
  212. }
  213. if ( ! $path) {
  214. return null;
  215. }
  216. return implode(' -> ', $path);
  217. }
  218. private function afterVisitingObject(VisitorInterface $visitor, ClassMetadata $metadata, $object, array $type)
  219. {
  220. if (self::DIRECTION_SERIALIZATION === $this->direction) {
  221. $this->visiting->detach($object);
  222. foreach ($metadata->postSerializeMethods as $method) {
  223. $method->invoke($object);
  224. }
  225. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.post_serialize', $metadata->name, $this->format)) {
  226. $this->dispatcher->dispatch('serializer.post_serialize', $metadata->name, $this->format, new Event($visitor, $object, $type));
  227. }
  228. return;
  229. }
  230. foreach ($metadata->postDeserializeMethods as $method) {
  231. $method->invoke($object);
  232. }
  233. if (null !== $this->dispatcher && $this->dispatcher->hasListeners('serializer.post_deserialize', $metadata->name, $this->format)) {
  234. $this->dispatcher->dispatch('serializer.post_deserialize', $metadata->name, $this->format, new Event($visitor, $object, $type));
  235. }
  236. }
  237. }