1<?php
2
3declare(strict_types=1);
4
5namespace JMS\Serializer\Handler;
6
7use JMS\Serializer\GraphNavigatorInterface;
8use JMS\Serializer\Metadata\StaticPropertyMetadata;
9use JMS\Serializer\SerializationContext;
10use JMS\Serializer\Visitor\SerializationVisitorInterface;
11
12/**
13 * @author Asmir Mustafic <goetas@gmail.com>
14 */
15final class StdClassHandler implements SubscribingHandlerInterface
16{
17    /**
18     * {@inheritdoc}
19     */
20    public static function getSubscribingMethods()
21    {
22        $methods = [];
23        $formats = ['json', 'xml', 'yml'];
24
25        foreach ($formats as $format) {
26            $methods[] = [
27                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
28                'type' => 'stdClass',
29                'format' => $format,
30                'method' => 'serializeStdClass',
31            ];
32        }
33
34        return $methods;
35    }
36
37    /**
38     * @return mixed
39     */
40    public function serializeStdClass(SerializationVisitorInterface $visitor, \stdClass $stdClass, array $type, SerializationContext $context)
41    {
42        $classMetadata = $context->getMetadataFactory()->getMetadataForClass('stdClass');
43        $visitor->startVisitingObject($classMetadata, $stdClass, ['name' => 'stdClass'], $context);
44
45        foreach ((array) $stdClass as $name => $value) {
46            $metadata = new StaticPropertyMetadata('stdClass', $name, $value);
47            $visitor->visitProperty($metadata, $value);
48        }
49
50        return $visitor->endVisitingObject($classMetadata, $stdClass, ['name' => 'stdClass'], $context);
51    }
52}
53