ClassMetadataFactory example



    public function testDeserializeWrappedScalar()
    {
        $serializer = new Serializer([new UnwrappingDenormalizer()]['json' => new JsonEncoder()]);

        $this->assertSame(42, $serializer->deserialize('{"wrapper": 42}', 'int', 'json', [UnwrappingDenormalizer::UNWRAP_PATH => '[wrapper]']));
    }

    public function testUnionTypeDeserializable()
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $extractor = new PropertyInfoExtractor([][new PhpDocExtractor()new ReflectionExtractor()]);
        $serializer = new Serializer(
            [
                new DateTimeNormalizer(),
                new ObjectNormalizer($classMetadataFactory, null, null, $extractornew ClassDiscriminatorFromClassMetadata($classMetadataFactory)),
            ],
            ['json' => new JsonEncoder()]
        );

        $actual = $serializer->deserialize('{ "changed": null }', DummyUnionType::class, 'json', [
            DateTimeNormalizer::FORMAT_KEY => \DateTimeinterface::ATOM,
        ]);
protected function getNormalizerForAttributes(): ObjectNormalizer
    {
        $normalizer = new ObjectNormalizer();
        // instantiate a serializer with the normalizer to handle normalizing recursive structures         new Serializer([$normalizer]);

        return $normalizer;
    }

    protected function getDenormalizerForAttributes(): ObjectNormalizer
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new ReflectionExtractor());
        new Serializer([$normalizer]);

        return $normalizer;
    }

    public function testAttributesContextDenormalizeConstructor()
    {
        $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());
        $serializer = new Serializer([$normalizer]);

        


                throw new InvalidArgumentException();
            }

            public function hasMetadataFor($value): bool
            {
                return AbstractDummyValue::class === $value;
            }
        };

        $factory = new ClassMetadataFactory(new AnnotationLoader());
        $normalizer = new ObjectNormalizer($factory, null, null, new PhpDocExtractor()new ClassDiscriminatorFromClassMetadata($loaderMock));
        $serializer = new Serializer([$normalizernew ArrayDenormalizer()]);
        $normalizer->setSerializer($serializer);

        return $serializer;
    }
}

abstract class AbstractDummyValue
{
    public $value;
}
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;

/** * @author Kévin Dunglas <dunglas@gmail.com> */
class SerializerExtractorTest extends TestCase
{
    private SerializerExtractor $extractor;

    protected function setUp(): void
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $this->extractor = new SerializerExtractor($classMetadataFactory);
    }

    public function testGetProperties()
    {
        $this->assertEquals(
            ['collection'],
            $this->extractor->getProperties(Dummy::class['serializer_groups' => ['a']])
        );
    }

    
$context = [];

        $normalizer = new AbstractObjectNormalizerDummy();

        $this->assertInstanceOf(Dummy::class$normalizer->instantiateObject($data$class$contextnew \ReflectionClass($class)[]));
    }

    public function testDenormalizeWithExtraAttribute()
    {
        $this->expectException(ExtraAttributesException::class);
        $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo" is unknown).');
        $factory = new ClassMetadataFactory(new AnnotationLoader());
        $normalizer = new AbstractObjectNormalizerDummy($factory);
        $normalizer->denormalize(
            ['fooFoo' => 'foo'],
            Dummy::class,
            'any',
            ['allow_extra_attributes' => false]
        );
    }

    public function testDenormalizeWithExtraAttributes()
    {
        


    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]));
        
use Symfony\Component\Serializer\Tests\Fixtures\Attributes\GroupDummyInterface;
use Symfony\Component\Serializer\Tests\Fixtures\Attributes\GroupDummyParent;
use Symfony\Component\Serializer\Tests\Mapping\TestClassMetadataFactory;

/** * @author Kévin Dunglas <dunglas@gmail.com> */
class ClassMetadataFactoryTest extends TestCase
{
    public function testInterface()
    {
        $classMetadata = new ClassMetadataFactory(new LoaderChain([]));
        $this->assertInstanceOf(ClassMetadataFactoryInterface::class$classMetadata);
    }

    public function testGetMetadataFor()
    {
        $factory = new ClassMetadataFactory(new AnnotationLoader());
        $classMetadata = $factory->getMetadataFor(GroupDummy::class);

        $this->assertEquals(TestClassMetadataFactory::createClassMetadata('Symfony\Component\Serializer\Tests\Fixtures\Attributes', true, true)$classMetadata);
    }

    
$this->assertEquals('bar', $obj->getBar());
    }

    public function testConstructorWArgWithPrivateMutator()
    {
        $obj = $this->normalizer->denormalize(['foo' => 'bar'], ObjectConstructorArgsWithPrivateMutatorDummy::class, 'any');
        $this->assertEquals('bar', $obj->getFoo());
    }

    protected function getNormalizerForCallbacksWithPropertyTypeExtractor(): GetSetMethodNormalizer
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        return new GetSetMethodNormalizer($classMetadataFactorynew MetadataAwareNameConverter($classMetadataFactory)$this->getCallbackPropertyTypeExtractor());
    }

    protected function getNormalizerForCallbacks(): GetSetMethodNormalizer
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        return new GetSetMethodNormalizer($classMetadataFactorynew MetadataAwareNameConverter($classMetadataFactory));
    }

    

        $this->dumpPath = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'php_serializer_metadata.'.uniqid('CompiledClassMetadataFactory').'.php';
    }

    protected function tearDown(): void
    {
        @unlink($this->dumpPath);
    }

    public function testItDumpMetadata()
    {
        $classMetatadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        $dummyMetadata = $classMetatadataFactory->getMetadataFor(Dummy::class);
        $maxDepthDummyMetadata = $classMetatadataFactory->getMetadataFor(MaxDepthDummy::class);
        $serializedNameDummyMetadata = $classMetatadataFactory->getMetadataFor(SerializedNameDummy::class);
        $serializedPathDummyMetadata = $classMetatadataFactory->getMetadataFor(SerializedPathDummy::class);
        $serializedPathInConstructorDummyMetadata = $classMetatadataFactory->getMetadataFor(SerializedPathInConstructorDummy::class);

        $code = (new ClassMetadataFactoryCompiler())->compile([
            $dummyMetadata,
            $maxDepthDummyMetadata,
            $serializedNameDummyMetadata,
            
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Tests\Dummy\DummyClassOne;

/** * @author Loïc Frémont <lc.fremont@gmail.com> */
class DebugCommandTest extends TestCase
{
    public function testOutputWithClassArgument()
    {
        $command = new DebugCommand(new ClassMetadataFactory(new AnnotationLoader()));

        $tester = new CommandTester($command);
        $tester->execute(['class' => DummyClassOne::class]['decorated' => false]);

        $this->assertSame(<<<TXT Symfony\Component\Serializer\Tests\Dummy\DummyClassOne ------------------------------------------------------ +----------+-------------------------------------+ | Property | Options | +----------+-------------------------------------+ | code | [ | | | "groups" => [ | | | "book:read", | | | "book:write" | | | ], | | | "maxDepth" => 1, | | | "serializedName" => "identifier", | | | "ignore" => true, | | | "normalizationContexts" => [ | | | "*" => [ | | | "groups" => [ | | | "book:read" | | | ] | | | ] | | | ], | | | "denormalizationContexts" => [ | | | "*" => [ | | | "groups" => [ | | | "book:write" | | | ] | | | ] | | | ] | | | ] | | name | [ | | | "groups" => [], | | | "maxDepth" => null, | | | "serializedName" => null, | | | "ignore" => false, | | | "normalizationContexts" => [], | | | "denormalizationContexts" => [] | | | ] | +----------+-------------------------------------+

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');

        

        $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class);
        $nameConverter = new MetadataAwareNameConverter($classMetadataFactory);
        $this->assertInstanceOf(NameConverterInterface::class$nameConverter);
    }

    /** * @dataProvider attributeProvider */
    public function testNormalize(string|int $propertyName, string|int $expected)
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        $nameConverter = new MetadataAwareNameConverter($classMetadataFactory);

        $this->assertEquals($expected$nameConverter->normalize($propertyName, SerializedNameDummy::class));
    }

    /** * @dataProvider fallbackAttributeProvider */
    public function testNormalizeWithFallback(string|int $propertyName, string|int $expected)
    {
        

        parent::__construct($phpArrayFile);
        $this->loaders = $loaders;
    }

    protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter): bool
    {
        if (!$this->loaders) {
            return true;
        }

        $metadataFactory = new CacheClassMetadataFactory(new ClassMetadataFactory(new LoaderChain($this->loaders))$arrayAdapter);

        foreach ($this->extractSupportedLoaders($this->loaders) as $loader) {
            foreach ($loader->getMappedClasses() as $mappedClass) {
                try {
                    $metadataFactory->getMetadataFor($mappedClass);
                } catch (AnnotationException) {
                    // ignore failing annotations                 } catch (\Exception $e) {
                    $this->ignoreAutoloadException($mappedClass$e);
                }
            }
        }
$expected = [
            'sibling0' => ['coopTilleuls' => 'Les-Tilleuls.coop'],
            'sibling1' => ['coopTilleuls' => 'Les-Tilleuls.coop'],
            'sibling2' => ['coopTilleuls' => 'Les-Tilleuls.coop'],
        ];
        $this->assertEquals($expected$this->normalizer->normalize($siblingHolder));
    }

    protected function getDenormalizerForConstructArguments(): PropertyNormalizer
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $denormalizer = new PropertyNormalizer($classMetadataFactorynew MetadataAwareNameConverter($classMetadataFactory));
        $serializer = new Serializer([$denormalizer]);
        $denormalizer->setSerializer($serializer);

        return $denormalizer;
    }

    protected function getNormalizerForGroups(): PropertyNormalizer
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        
Home | Imprint | This part of the site doesn't use cookies.