BackedEnumNormalizer example

use Symfony\Component\Serializer\Tests\Fixtures\UnitEnumDummy;

/** * @author Alexandre Daubois <alex.daubois@gmail.com> */
class BackedEnumNormalizerTest extends TestCase
{
    private BackedEnumNormalizer $normalizer;

    protected function setUp(): void
    {
        $this->normalizer = new BackedEnumNormalizer();
    }

    public function testSupportsNormalization()
    {
        $this->assertTrue($this->normalizer->supportsNormalization(StringBackedEnumDummy::GET));
        $this->assertTrue($this->normalizer->supportsNormalization(IntegerBackedEnumDummy::SUCCESS));
        $this->assertFalse($this->normalizer->supportsNormalization(UnitEnumDummy::GET));
        $this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
    }

    public function testNormalize()
    {


        $serializer = new Serializer([$normalizer]);
        $serializer->normalize($object);

        $this->assertSame('called', $object->bar);
    }

    public function testDenormalizeUnionOfEnums()
    {
        $serializer = new Serializer([
            new BackedEnumNormalizer(),
            new ObjectNormalizer(
                classMetadataFactory: new ClassMetadataFactory(new AnnotationLoader()),
                propertyTypeExtractor: new PropertyInfoExtractor([][new ReflectionExtractor()]),
            ),
        ]);

        $normalized = $serializer->normalize(new DummyWithEnumUnion(EnumA::A));
        $this->assertEquals(new DummyWithEnumUnion(EnumA::A)$serializer->denormalize($normalized, DummyWithEnumUnion::class));

        $normalized = $serializer->normalize(new DummyWithEnumUnion(EnumB::B));
        $this->assertEquals(new DummyWithEnumUnion(EnumB::B)$serializer->denormalize($normalized, DummyWithEnumUnion::class));
    }
'message' => 'The type of the "bool" attribute for class "Symfony\\Component\\Serializer\\Tests\\Fixtures\\Php80WithPromotedTypedConstructor" must be one of "bool" ("string" given).',
            ],
        ];

        $this->assertSame($expected$exceptionsAsArray);
    }

    public function testCollectDenormalizationErrorsWithEnumConstructor()
    {
        $serializer = new Serializer(
            [
                new BackedEnumNormalizer(),
                new ObjectNormalizer(),
            ],
            ['json' => new JsonEncoder()]
        );

        try {
            $serializer->deserialize('{"invalid": "GET"}', DummyObjectWithEnumConstructor::class, 'json', [
                DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true,
            ]);
        } catch (\Throwable $th) {
            $this->assertInstanceOf(PartialDenormalizationException::class$th);
        }
Home | Imprint | This part of the site doesn't use cookies.