AnnotationLoader example

$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));
    }

    

        $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)
    {
        


    public static function serializerDataProvider(): \Generator
    {
        yield ['{{ object|serialize }}', '{"name":"howdy","title":"fixture"}'];
        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]));
        
$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()
    {
        
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']])
        );
    }

    

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

        


        foreach ($this->yamlMappings as $yamlMappings) {
            $loaders[] = new YamlFileLoader($yamlMappings);
        }

        foreach ($this->methodMappings as $methodName) {
            $loaders[] = new StaticMethodLoader($methodName);
        }

        if ($this->enableAttributeMapping && $this->annotationReader) {
            $loaders[] = new AnnotationLoader($this->annotationReader);
        } elseif ($this->enableAttributeMapping) {
            $loaders[] = new AttributeLoader();
        }

        return array_merge($loaders$this->loaders);
    }

    /** * Builds and returns a new validator object. */
    public function getValidator(): ValidatorInterface
    {


    public function testLoadGroupSequenceProviderAnnotation()
    {
        $this->expectDeprecation('Since symfony/validator 6.4: Class "Symfony\Component\Validator\Tests\Fixtures\Annotation\GroupSequenceProviderEntity" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');

        parent::testLoadGroupSequenceProviderAnnotation();
    }

    protected function createAnnotationLoader(): AnnotationLoader
    {
        return new AnnotationLoader(new AnnotationReader());
    }

    protected function getFixtureNamespace(): string
    {
        return 'Symfony\Component\Validator\Tests\Fixtures\Annotation';
    }
}
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]);

        
namespace Symfony\Component\Serializer\Tests\Mapping\Loader;

use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\ClassMetadata;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;

class AnnotationLoaderWithAttributesTest extends AnnotationLoaderTestCase
{
    protected function createLoader(): AnnotationLoader
    {
        return new AnnotationLoader();
    }

    protected function getNamespace(): string
    {
        return 'Symfony\Component\Serializer\Tests\Fixtures\Attributes';
    }

    public function testLoadWithInvalidAttribute()
    {
        $this->expectException(MappingException::class);
        $this->expectExceptionMessage('Could not instantiate attribute "Symfony\Component\Serializer\Annotation\Groups" on "Symfony\Component\Serializer\Tests\Fixtures\Attributes\BadAttributeDummy::myMethod()".');

        
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" => [] | | | ] | +----------+-------------------------------------+
$this->expectExceptionMessage('The value "foo" is not an instance of Constraint in constraint "Symfony\Component\Validator\Constraints\When"');
        new When('true', [
            'foo',
        ]);
    }

    /** * @group legacy */
    public function testAnnotations()
    {
        $loader = new AnnotationLoader(new AnnotationReader());
        $metadata = new ClassMetadata(WhenTestWithAnnotations::class);

        $this->expectDeprecation('Since symfony/validator 6.4: Class "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');
        $this->expectDeprecation('Since symfony/validator 6.4: Property "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::$foo" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');
        $this->expectDeprecation('Since symfony/validator 6.4: Property "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::$bar" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');
        $this->expectDeprecation('Since symfony/validator 6.4: Property "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::$qux" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');
        $this->expectDeprecation('Since symfony/validator 6.4: Method "Symfony\Component\Validator\Tests\Constraints\WhenTestWithAnnotations::getBaz()" uses Doctrine Annotations to configure validation constraints, which is deprecated. Use PHP attributes instead.');

        self::assertTrue($loader->loadClassMetadata($metadata));

        [$classConstraint] = $metadata->getConstraints();

        
$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());

        


    public function testIgnoreGetterWithRequiredParameterIfIgnoreAnnotationIsUsed()
    {
        $this->expectDeprecation('Since symfony/serializer 6.4: Method "Symfony\Component\Serializer\Tests\Fixtures\Annotations\IgnoreDummyAdditionalGetter::getMyValue()" uses Doctrine Annotations to configure serialization, which is deprecated. Use PHP attributes instead.');

        parent::testIgnoreGetterWithRequiredParameterIfIgnoreAnnotationIsUsed();
    }

    protected function createLoader(): AnnotationLoader
    {
        return new AnnotationLoader(new AnnotationReader());
    }

    protected function getNamespace(): string
    {
        return 'Symfony\Component\Serializer\Tests\Fixtures\Annotations';
    }
}

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

    public function testHasMetadataFor()
    {
        $factory = new ClassMetadataFactory(new AnnotationLoader());
        $this->assertTrue($factory->hasMetadataFor(GroupDummy::class));
        $this->assertTrue($factory->hasMetadataFor(GroupDummyParent::class));
        $this->assertTrue($factory->hasMetadataFor(GroupDummyInterface::class));
        
Home | Imprint | This part of the site doesn't use cookies.