Forráskód Böngészése

moved logic to a custom handler

Johannes Schmitt 13 éve
szülő
commit
a544bab7e6

+ 2 - 15
Serializer/GraphNavigator.php

@@ -68,22 +68,9 @@ final class GraphNavigator
                 $this->visiting->attach($data);
             }
 
+            // try custom handler
             $handled = false;
-
-            if ($isSerialization) {
-                if ($data instanceof SerializationHandlerInterface) {
-                    $rs = $data->serialize($visitor, $data, $type, $handled);
-                }
-            } elseif (in_array('JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface', class_implements($type))) {
-                $handler = new $type;
-                $rs = $handler->deserialize($visitor, $data, $type, $handled);
-            }
-
-            if (!$handled) {
-                 // try custom handler
-                $rs = $visitor->visitUsingCustomHandler($data, $type, $handled);
-            }
-
+            $rs = $visitor->visitUsingCustomHandler($data, $type, $handled);
             if ($handled) {
                 if ($isSerialization) {
                     $this->visiting->detach($data);

+ 43 - 0
Serializer/Handler/ObjectBasedCustomHandler.php

@@ -0,0 +1,43 @@
+<?php
+
+namespace JMS\SerializerBundle\Serializer\Handler;
+
+use Metadata\MetadataFactoryInterface;
+
+use JMS\SerializerBundle\Serializer\VisitorInterface;
+use JMS\SerializerBundle\Serializer\Construction\ObjectConstructorInterface;
+
+class ObjectBasedCustomHandler implements SerializationHandlerInterface, DeserializationHandlerInterface
+{
+    private $objectConstructor;
+    private $metadataFactory;
+
+    public function __construct(ObjectConstructorInterface $constructor, MetadataFactoryInterface $metadata)
+    {
+        $this->objectConstructor = $objectConstructor;
+        $this->metadataFactory = $metadataFactory;
+    }
+
+    public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
+    {
+        if (!$data instanceof SerializationHandlerInterface) {
+            return;
+        }
+
+        return $data->serialize($visitor, $data, $type, $handled);
+    }
+
+    public function deserialize(VisitorInterface $visitor, $data, $type, &$handled)
+    {
+        if (!is_a($type, 'JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface')) {
+            return;
+        }
+
+        $metadata = $this->metadataFactory->getMetadataForClass($type);
+
+        $instance = $this->objectConstructor->construct($visitor, $metadata, $data, $type);
+        $instance->deserialize($visitor, $data, $type, $handled);
+
+        return $instance;
+    }
+}