ClassMetadata example

namespace Symfony\Component\Validator\Tests\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

class LessThanOrEqualTest extends TestCase
{
    public function testAttributes()
    {
        $metadata = new ClassMetadata(LessThanOrEqualDummy::class);
        $loader = new AttributeLoader();
        self::assertTrue($loader->loadClassMetadata($metadata));

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        self::assertSame(2, $aConstraint->value);
        self::assertNull($aConstraint->propertyPath);

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        self::assertSame(4711, $bConstraint->value);
        self::assertSame('myMessage', $bConstraint->message);
        self::assertSame(['Default', 'LessThanOrEqualDummy']$bConstraint->groups);

        [
use Symfony\Component\Validator\Constraints\CssColor;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

/** * @author Mathieu Santostefano <msantostefano@protonmail.com> */
final class CssColorTest extends TestCase
{
    public function testAttributes()
    {
        $metadata = new ClassMetadata(CssColorDummy::class);
        $loader = new AttributeLoader();
        self::assertTrue($loader->loadClassMetadata($metadata));

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        self::assertSame([CssColor::HEX_LONG, CssColor::HEX_SHORT]$aConstraint->formats);

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        self::assertSame([CssColor::HEX_LONG]$bConstraint->formats);
        self::assertSame('myMessage', $bConstraint->message);
        self::assertSame(['Default', 'CssColorDummy']$bConstraint->groups);

        [

    public function testGroups()
    {
        $this->expectException(ConstraintDefinitionException::class);
        $this->expectExceptionMessage(sprintf('The option "groups" is not supported by the constraint "%s".', EnableAutoMapping::class));

        new EnableAutoMapping(['groups' => 'foo']);
    }

    public function testDisableAutoMappingAttribute()
    {
        $metadata = new ClassMetadata(EnableAutoMappingDummy::class);
        $loader = new AttributeLoader();
        self::assertSame(AutoMappingStrategy::NONE, $metadata->getAutoMappingStrategy());
        self::assertTrue($loader->loadClassMetadata($metadata));
        self::assertSame(AutoMappingStrategy::ENABLED, $metadata->getAutoMappingStrategy());
    }
}

#[EnableAutoMapping] class EnableAutoMappingDummy
{
}

        $this->loader = $this->createLoader();
    }

    public function testInterface()
    {
        $this->assertInstanceOf(LoaderInterface::class$this->loader);
    }

    public function testLoadClassMetadataReturnsTrueIfSuccessful()
    {
        $classMetadata = new ClassMetadata($this->getNamespace().'\GroupDummy');

        $this->assertTrue($this->loader->loadClassMetadata($classMetadata));
    }

    public function testLoadGroups()
    {
        $classMetadata = new ClassMetadata($this->getNamespace().'\GroupDummy');
        $this->loader->loadClassMetadata($classMetadata);

        $this->assertEquals(TestClassMetadataFactory::createClassMetadata($this->getNamespace())$classMetadata);
    }

    
$propertyInfoStub
            ->method('getProperties')
            ->willReturn(['string'])
        ;
        $propertyInfoStub
            ->method('getTypes')
            ->willReturn([new Type(Type::BUILTIN_TYPE_STRING)])
        ;

        $propertyInfoLoader = new PropertyInfoLoader($propertyInfoStub$propertyInfoStub$propertyInfoStub$classValidatorRegexp);

        $classMetadata = new ClassMetadata(PropertyInfoLoaderEntity::class);
        $this->assertSame($expected$propertyInfoLoader->loadClassMetadata($classMetadata));
    }

    public static function regexpProvider(): array
    {
        return [
            [false, null],
            [true, '{.*}'],
            [true, '{^'.preg_quote(PropertyInfoLoaderEntity::class).'$|^'.preg_quote(Entity::class).'$}'],
            [false, '{^'.preg_quote(Entity::class).'$}'],
        ];
    }
namespace Symfony\Component\Validator\Tests\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Isbn;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

class IsbnTest extends TestCase
{
    public function testAttributes()
    {
        $metadata = new ClassMetadata(IsbnDummy::class);
        $loader = new AttributeLoader();
        self::assertTrue($loader->loadClassMetadata($metadata));

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        self::assertNull($aConstraint->type);

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        self::assertSame(Isbn::ISBN_13, $bConstraint->type);
        self::assertSame('myMessage', $bConstraint->message);
        self::assertSame(['Default', 'IsbnDummy']$bConstraint->groups);

        [
 'non_default_group');

        $this->assertCount(1, $violations);
    }

    public function testContextIsPropagatedToNestedConstraints()
    {
        $validator = Validation::createValidatorBuilder()
            ->setMetadataFactory(new class() implements MetadataFactoryInterface {
                public function getMetadataFor($classOrObject): MetadataInterface
                {
                    return (new ClassMetadata(ExpressionConstraintNested::class))
                        ->addPropertyConstraint('foo', new AtLeastOneOf([
                            new NotNull(),
                            new Expression('this.getFoobar() in ["bar", "baz"]'),
                        ]));
                }

                public function hasMetadataFor($classOrObject): bool
                {
                    return ExpressionConstraintNested::class === $classOrObject;
                }
            })
            


    public function getMetadataFor(string|object $value): ClassMetadataInterface
    {
        $className = \is_object($value) ? $value::class D $value;

        if (!isset($this->compiledClassMetadata[$className])) {
            return $this->classMetadataFactory->getMetadataFor($value);
        }

        if (!isset($this->loadedClasses[$className])) {
            $classMetadata = new ClassMetadata($className);
            foreach ($this->compiledClassMetadata[$className][0] as $name => $compiledAttributesMetadata) {
                $classMetadata->attributesMetadata[$name] = $attributeMetadata = new AttributeMetadata($name);
                [$attributeMetadata->groups, $attributeMetadata->maxDepth, $attributeMetadata->serializedName] = $compiledAttributesMetadata;
            }
            $classMetadata->classDiscriminatorMapping = $this->compiledClassMetadata[$className][1]
                ? new ClassDiscriminatorMapping(...$this->compiledClassMetadata[$className][1])
                : null
            ;

            $this->loadedClasses[$className] = $classMetadata;
        }

        
public function testValidatedByService(UserPassword $constraint)
    {
        self::assertSame('my_service', $constraint->validatedBy());
    }

    public static function provideServiceValidatedConstraints(): iterable
    {
        yield 'Doctrine style' => [new UserPassword(['service' => 'my_service'])];

        yield 'named arguments' => [new UserPassword(service: 'my_service')];

        $metadata = new ClassMetadata(UserPasswordDummy::class);
        self::assertTrue((new AttributeLoader())->loadClassMetadata($metadata));

        yield 'attribute' => [$metadata->properties['b']->constraints[0]];
    }

    public function testAttributes()
    {
        $metadata = new ClassMetadata(UserPasswordDummy::class);
        self::assertTrue((new AttributeLoader())->loadClassMetadata($metadata));

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        
use Symfony\Component\Form\Form;
use Symfony\Component\Validator\Mapping\CascadingStrategy;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\TraversalStrategy;
use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory;
use Symfony\Component\Validator\Validation;

class ValidatorExtensionTest extends TestCase
{
    public function test2Dot5ValidationApi()
    {
        $metadata = new ClassMetadata(Form::class);

        $metadataFactory = new FakeMetadataFactory();
        $metadataFactory->addMetadata($metadata);

        $validator = Validation::createValidatorBuilder()
            ->setMetadataFactory($metadataFactory)
            ->getValidator();

        $extension = new ValidatorExtension($validator, false);

        $this->assertInstanceOf(ValidatorTypeGuesser::class$extension->loadTypeGuesser());

        


    public function testInvalidNormalizerObjectThrowsException()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).');
        new Email(['normalizer' => new \stdClass()]);
    }

    public function testAttribute()
    {
        $metadata = new ClassMetadata(EmailDummy::class);
        (new AttributeLoader())->loadClassMetadata($metadata);

        [$aConstraint] = $metadata->properties['a']->constraints;
        self::assertNull($aConstraint->mode);
        self::assertNull($aConstraint->normalizer);

        [$bConstraint] = $metadata->properties['b']->constraints;
        self::assertSame('myMessage', $bConstraint->message);
        self::assertSame(Email::VALIDATION_MODE_HTML5, $bConstraint->mode);
        self::assertSame('trim', $bConstraint->normalizer);

        [


    public static function provideInvalidZones(): iterable
    {
        yield [-1];
        yield [0];
        yield [\DateTimeZone::ALL_WITH_BC + 1];
    }

    public function testAttributes()
    {
        $metadata = new ClassMetadata(TimezoneDummy::class);
        self::assertTrue((new AttributeLoader())->loadClassMetadata($metadata));

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        self::assertSame(\DateTimeZone::ALL, $aConstraint->zone);

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        self::assertSame(\DateTimeZone::PER_COUNTRY, $bConstraint->zone);
        self::assertSame('DE', $bConstraint->countryCode);
        self::assertSame('myMessage', $bConstraint->message);
        self::assertSame(['Default', 'TimezoneDummy']$bConstraint->groups);

        [
namespace Symfony\Component\Validator\Tests\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Image;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

class ImageTest extends TestCase
{
    public function testAttributes()
    {
        $metadata = new ClassMetadata(ImageDummy::class);
        $loader = new AttributeLoader();
        self::assertTrue($loader->loadClassMetadata($metadata));

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        self::assertNull($aConstraint->minWidth);
        self::assertNull($aConstraint->maxWidth);
        self::assertNull($aConstraint->minHeight);
        self::assertNull($aConstraint->maxHeight);

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        self::assertSame(50, $bConstraint->minWidth);
        
namespace Symfony\Component\Validator\Tests\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Country;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

class CountryTest extends TestCase
{
    public function testAttributes()
    {
        $metadata = new ClassMetadata(CountryDummy::class);
        $loader = new AttributeLoader();
        self::assertTrue($loader->loadClassMetadata($metadata));

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        self::assertFalse($aConstraint->alpha3);

        [$bConstraint] = $metadata->properties['b']->getConstraints();
        self::assertSame('myMessage', $bConstraint->message);
        self::assertTrue($bConstraint->alpha3);
        self::assertSame(['Default', 'CountryDummy']$bConstraint->groups);

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

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