Ejemplo n.º 1
0
 public function testSerializationContextPathAndDepth()
 {
     $object = new Node([new Node(), new Node([new Node()])]);
     $objects = [$object, $object->children[0], $object->children[1], $object->children[1]->children[0]];
     $navigator = $this->getMockBuilder(GraphNavigator::class)->disableOriginalConstructor()->getMock();
     $context = new SerializationContext();
     $context->initialize('json', $this->createMock(VisitorInterface::class), $navigator, $this->createMock(MetadataFactoryInterface::class));
     $context->startVisiting($objects[0]);
     $this->assertEquals(1, $context->getDepth());
     $context->startVisiting($objects[1]);
     $this->assertEquals(2, $context->getDepth());
     $context->startVisiting($objects[2]);
     $this->assertEquals(3, $context->getDepth());
 }
Ejemplo n.º 2
0
 private function serialize($data, Type $type, SerializationContext $context)
 {
     $inVisitingStack = is_object($data) && null !== $data && !$context->getMetadataStack()->getCurrent() instanceof AdditionalPropertyMetadata;
     if ($inVisitingStack) {
         if ($context->isVisiting($data)) {
             return null;
         }
         $context->startVisiting($data);
     }
     // If we're serializing a polymorphic type, then we'll be interested in the
     // metadata for the actual type of the object, not the base class.
     if (is_subclass_of($data, $type->getName(), false)) {
         $type = new Type(get_class($data));
     }
     if (null !== $this->dispatcher && !is_scalar($data)) {
         $this->dispatcher->dispatch(Events::PRE_SERIALIZE, $event = new PreSerializeEvent($context, $data, $type));
         $data = $event->getData();
     }
     $metadata = $this->getMetadataForType($type);
     if (null !== $metadata) {
         foreach ($metadata->preSerializeMethods as $method) {
             $method->getReflection()->invoke($data);
         }
     }
     $context->getVisitor()->startVisiting($data, $type, $context);
     $this->callVisitor($data, $type, $context, $metadata);
     if (null !== $metadata) {
         foreach ($metadata->postSerializeMethods as $method) {
             $method->getReflection()->invoke($data);
         }
     }
     if (null !== $this->dispatcher && !is_scalar($data)) {
         $this->dispatcher->dispatch(Events::POST_SERIALIZE, new PostSerializeEvent($context, $data, $type));
     }
     $rs = $context->getVisitor()->endVisiting($data, $type, $context);
     if ($inVisitingStack) {
         $context->stopVisiting($data);
     }
     return $rs;
 }