ObjectNormalizer example


trait ContextMetadataTestTrait
{
    /** * @dataProvider contextMetadataDummyProvider */
    public function testContextMetadataNormalize(string $contextMetadataDummyClass)
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new PhpDocExtractor());
        new Serializer([new DateTimeNormalizer()$normalizer]);

        $dummy = new $contextMetadataDummyClass();
        $dummy->date = new \DateTimeImmutable('2011-07-28T08:44:00.123+00:00');

        self::assertEquals(['date' => '2011-07-28T08:44:00+00:00']$normalizer->normalize($dummy));

        self::assertEquals(['date' => '2011-07-28T08:44:00.123+00:00']$normalizer->normalize($dummy, null, [
            ObjectNormalizer::GROUPS => 'extended',
        ]), 'a specific normalization context is used for this group');

        
'id' => 1,
            'body' => '{"message": "Hi"}',
            'headers' => [
                'type' => DummyMessage::class,
            ],
        ];
    }

    private function createSerializer(): Serializer
    {
        $serializer = new Serializer(
            new SerializerComponent\Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()])
        );

        return $serializer;
    }
}
public function testSerializeArrayOfScalars()
    {
        $serializer = new Serializer([]['json' => new JsonEncoder()]);
        $data = ['foo', [5, 3]];
        $result = $serializer->serialize($data, 'json');
        $this->assertEquals(json_encode($data)$result);
    }

    public function testSerializeEmpty()
    {
        $serializer = new Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()]);
        $data = ['foo' => new \stdClass()];

        // Old buggy behaviour         $result = $serializer->serialize($data, 'json');
        $this->assertEquals('{"foo":[]}', $result);

        $result = $serializer->serialize($data, 'json', ['preserve_empty_objects' => true]);
        $this->assertEquals('{"foo":{}}', $result);
    }

    public function testSerializeNoEncoder()
    {

    public function testPropertyPhpDoc($class)
    {
        $json = <<<EOF { "animals": [ {"name": "Bug"} ] } EOF;
        $serializer = new Serializer([
            new ObjectNormalizer(null, null, null, new PhpDocExtractor()),
            new ArrayDenormalizer(),
        ]['json' => new JsonEncoder()]);

        /** @var Zoo|ZooImmutable $zoo */
        $zoo = $serializer->deserialize($json$class, 'json');

        self::assertCount(1, $zoo->getAnimals());
        self::assertInstanceOf(Animal::class$zoo->getAnimals()[0]);
    }

    public function testPropertyPhpDocWithKeyTypes()
    {
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

/** * @requires extension amqp */
class AmqpReceiverTest extends TestCase
{
    public function testItReturnsTheDecodedMessageToTheHandler()
    {
        $serializer = new Serializer(
            new SerializerComponent\Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()])
        );

        $amqpEnvelope = $this->createAMQPEnvelope();
        $connection = $this->createMock(Connection::class);
        $connection->method('getQueueNames')->willReturn(['queueName']);
        $connection->method('get')->with('queueName')->willReturn($amqpEnvelope);

        $receiver = new AmqpReceiver($connection$serializer);
        $actualEnvelopes = iterator_to_array($receiver->get());
        $this->assertCount(1, $actualEnvelopes);
        $this->assertEquals(new DummyMessage('Hi')$actualEnvelopes[0]->getMessage());
    }

        $normalizer = new StaticConstructorNormalizer();
        $dummy = $normalizer->denormalize(['foo' => 'baz'], StaticConstructorDummy::class);

        $this->assertInstanceOf(StaticConstructorDummy::class$dummy);
        $this->assertEquals('baz', $dummy->quz);
        $this->assertNull($dummy->foo);
    }

    public function testObjectWithNullableConstructorArgument()
    {
        $normalizer = new ObjectNormalizer();
        $dummy = $normalizer->denormalize(['foo' => null], NullableOptionalConstructorArgumentDummy::class);

        $this->assertNull($dummy->getFoo());
    }

    public function testObjectWithNullableConstructorArgumentWithoutInput()
    {
        $normalizer = new ObjectNormalizer();
        $dummy = $normalizer->denormalize([], NullableOptionalConstructorArgumentDummy::class);

        $this->assertNull($dummy->getFoo());
    }
EOF;

        $extractor = new PhpDocExtractor();
        $propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, TemplatedEmail::class, 'json');
        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n->from('fabien@symfony.com');
        
EOF;

        $extractor = new PhpDocExtractor();
        $propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        $this->assertSame($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, Email::class, 'json');
        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        $this->assertSame($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n->from('fabien@symfony.com');
        
foreach ($configuredSenders as $key => $sender) {
            $this->assertSame($sender$stampSenders[$key]);
        }
    }

    public function testDeserialization()
    {
        $stamp = new TransportNamesStamp(['foo']);
        $serializer = new Serializer(
            new SymfonySerializer([
                new ArrayDenormalizer(),
                new ObjectNormalizer(),
            ][new JsonEncoder()])
        );

        $deserializedEnvelope = $serializer->decode($serializer->encode(new Envelope(new \stdClass()[$stamp])));

        $deserializedStamp = $deserializedEnvelope->last(TransportNamesStamp::class);
        $this->assertInstanceOf(TransportNamesStamp::class$deserializedStamp);
        $this->assertEquals($stamp$deserializedStamp);
    }

    public function testGetIndividualSender()
    {
EOF;

        $extractor = new PhpDocExtractor();
        $propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json');
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, Message::class, 'json');
        $this->assertEquals($expected$n);

        $serialized = $serializer->serialize($e, 'json');
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
    }
'id' => '1',
            'body' => '{"message": "Hi"}',
            'headers' => [
                'type' => DummyMessage::class,
            ],
        ];
    }

    private function createSerializer(): Serializer
    {
        $serializer = new Serializer(
            new SerializerComponent\Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()])
        );

        return $serializer;
    }
}
private ObjectNormalizer $normalizer;
    private SerializerInterface&NormalizerInterface&MockObject $serializer;

    protected function setUp(): void
    {
        $this->createNormalizer();
    }

    private function createNormalizer(array $defaultContext = [], ClassMetadataFactoryInterface $classMetadataFactory = null): void
    {
        $this->serializer = $this->createMock(ObjectSerializerNormalizer::class);
        $this->normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext);
        $this->normalizer->setSerializer($this->serializer);
    }

    public function testNormalize()
    {
        $obj = new ObjectDummy();
        $object = new \stdClass();
        $obj->setFoo('foo');
        $obj->bar = 'bar';
        $obj->setBaz(true);
        $obj->setCamelCase('camelcase');
        
public static function serializerDataProvider(): \Generator
    {
        yield ['{{ object|serialize }}', '{&quot;name&quot;:&quot;howdy&quot;,&quot;title&quot;:&quot;fixture&quot;}'];
        yield ['{{ object|serialize(\'yaml\') }}', '{ name: howdy, title: fixture }'];
        yield ['{{ object|serialize(\'yaml\', {groups: \'read\'}) }}', '{ name: howdy }'];
    }

    private function getTwig(string $template): Environment
    {
        $meta = new ClassMetadataFactory(new AnnotationLoader());
        $runtime = new SerializerRuntime(new Serializer([new ObjectNormalizer($meta)][new JsonEncoder()new YamlEncoder()]));

        $mockRuntimeLoader = $this->createMock(RuntimeLoaderInterface::class);
        $mockRuntimeLoader
            ->method('load')
            ->willReturnMap([
                ['Symfony\Bridge\Twig\Extension\SerializerRuntime', $runtime],
            ])
        ;

        $twig = new Environment(new ArrayLoader(['template' => $template]));
        $twig->addExtension(new SerializerExtension());
        
'id' => 1,
            'body' => '{"message": "Hi"}',
            'headers' => [
                'type' => DummyMessage::class,
            ],
        ];
    }

    private function createSerializer(): Serializer
    {
        $serializer = new Serializer(
            new SerializerComponent\Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()])
        );

        return $serializer;
    }
}
$b = new \TSantos\Serializer\Normalizer\CollectionNormalizer();

        $c = new \TSantos\Serializer\EventDispatcher\EventDispatcher();
        $c->addSubscriber(new \TSantos\SerializerBundle\EventListener\StopwatchListener(new \Symfony\Component\Stopwatch\Stopwatch(true)));

        $container->services['tsantos_serializer'] = $instance = new \TSantos\Serializer\EventEmitterSerializer(new \TSantos\Serializer\Encoder\JsonEncoder()$a$c);

        $b->setSerializer($instance);
        $d = new \TSantos\Serializer\Normalizer\JsonNormalizer();
        $d->setSerializer($instance);

        $a->add(new \TSantos\Serializer\Normalizer\ObjectNormalizer(new \TSantos\SerializerBundle\Serializer\CircularReferenceHandler()));
        $a->add($b);
        $a->add($d);

        return $instance;
    }
}
Home | Imprint | This part of the site doesn't use cookies.