GraphNavigator.php 10 KB

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