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