addPropertyConstraint example



namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class EntityStaticCarTurbo extends EntityStaticCar
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('wheels', new Length(['max' => 99]));
    }
}
if (\count($groupSequence->value) > 0) {
                $metadata->setGroupSequence($this->parseValues($groupSequence[0]->value));
            }
        }

        foreach ($this->parseConstraints($classDescription->constraint) as $constraint) {
            $metadata->addConstraint($constraint);
        }

        foreach ($classDescription->property as $property) {
            foreach ($this->parseConstraints($property->constraint) as $constraint) {
                $metadata->addPropertyConstraint((string) $property['name']$constraint);
            }
        }

        foreach ($classDescription->getter as $getter) {
            foreach ($this->parseConstraints($getter->constraint) as $constraint) {
                $metadata->addGetterConstraint((string) $getter['property']$constraint);
            }
        }
    }
}


        if ($constraint instanceof Cascade) {
            $this->cascadingStrategy = CascadingStrategy::CASCADE;

            foreach ($this->getReflectionClass()->getProperties() as $property) {
                if (isset($constraint->exclude[$property->getName()])) {
                    continue;
                }

                if ($property->hasType() && (('array' === $type = $property->getType()->getName()) || class_exists($type))) {
                    $this->addPropertyConstraint($property->getName()new Valid());
                }
            }

            // The constraint is not added             return $this;
        }

        $constraint->addImplicitGroupName($this->getDefaultGroup());

        parent::addConstraint($constraint);

        
$this->assertCount(1, $form->get('field2')->getErrors());
    }
}

class Foo
{
    public $bar;
    public $baz;

    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $metadata->addPropertyConstraint('bar', new NotBlank());
    }
}

class FooType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('bar')
            ->add('baz', null, [
                'constraints' => [new NotBlank()],
            ])
if (true === ($mapping['unique'] ?? false) && !isset($existingUniqueFields[$mapping['fieldName']])) {
                $metadata->addConstraint(new UniqueEntity(['fields' => $mapping['fieldName']]));
                $loaded = true;
            }

            if (null === ($mapping['length'] ?? null) || null !== ($mapping['enumType'] ?? null) || !\in_array($mapping['type']['string', 'text'], true)) {
                continue;
            }

            if (null === $lengthConstraint) {
                if (isset($mapping['originalClass']) && !str_contains($mapping['declaredField'], '.')) {
                    $metadata->addPropertyConstraint($mapping['declaredField']new Valid());
                    $loaded = true;
                } elseif (property_exists($className$mapping['fieldName']) && (!$doctrineMetadata->isMappedSuperclass || $metadata->getReflectionClass()->getProperty($mapping['fieldName'])->isPrivate())) {
                    $metadata->addPropertyConstraint($mapping['fieldName']new Length(['max' => $mapping['length']]));
                    $loaded = true;
                }
            } elseif (null === $lengthConstraint->max) {
                // If a Length constraint exists and no max length has been explicitly defined, set it                 $lengthConstraint->max = $mapping['length'];
            }
        }

        
$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;
                }
            })
            ->getValidator()
        ;
if (isset($classDescription['constraints']) && \is_array($classDescription['constraints'])) {
            foreach ($this->parseNodes($classDescription['constraints']) as $constraint) {
                $metadata->addConstraint($constraint);
            }
        }

        if (isset($classDescription['properties']) && \is_array($classDescription['properties'])) {
            foreach ($classDescription['properties'] as $property => $constraints) {
                if (null !== $constraints) {
                    foreach ($this->parseNodes($constraints) as $constraint) {
                        $metadata->addPropertyConstraint($property$constraint);
                    }
                }
            }
        }

        if (isset($classDescription['getters']) && \is_array($classDescription['getters'])) {
            foreach ($classDescription['getters'] as $getter => $constraints) {
                if (null !== $constraints) {
                    foreach ($this->parseNodes($constraints) as $constraint) {
                        $metadata->addGetterConstraint($getter$constraint);
                    }
                }
 elseif ($constraint instanceof Constraint) {
                $metadata->addConstraint($constraint);
            }

            $success = true;
        }

        foreach ($reflClass->getProperties() as $property) {
            if ($property->getDeclaringClass()->name === $className) {
                foreach ($this->getAnnotations($property) as $constraint) {
                    if ($constraint instanceof Constraint) {
                        $metadata->addPropertyConstraint($property->name, $constraint);
                    }

                    $success = true;
                }
            }
        }

        foreach ($reflClass->getMethods() as $method) {
            if ($method->getDeclaringClass()->name === $className) {
                foreach ($this->getAnnotations($method) as $constraint) {
                    if ($constraint instanceof Callback) {
                        
 elseif ($constraint instanceof Constraint) {
                $metadata->addConstraint($constraint);
            }

            $success = true;
        }

        foreach ($reflClass->getProperties() as $property) {
            if ($property->getDeclaringClass()->name === $className) {
                foreach ($this->getAnnotations($property) as $constraint) {
                    if ($constraint instanceof Constraint) {
                        $metadata->addPropertyConstraint($property->name, $constraint);
                    }

                    $success = true;
                }
            }
        }

        foreach ($reflClass->getMethods() as $method) {
            if ($method->getDeclaringClass()->name === $className) {
                foreach ($this->getAnnotations($method) as $constraint) {
                    if ($constraint instanceof Callback) {
                        
namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class EntityStaticVehicle
{
    public $wheels;

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('wheels', new Length(['max' => 99]));
    }
}

    public function __construct(private readonly ValidatorInterface $validator)
    {
    }

    /** * Default method for determining constraints when using the Symfony validator. */
    public static function loadValidatorMetadata(ClassMetadata $metadata): void
    {
        $metadata->addPropertyConstraint('honeypotValue', new Blank());
    }

    /** * {@inheritdoc} */
    public function isValid(Request $request, array $captchaConfig): bool
    {
        $this->honeypotValue = $request->get(self::CAPTCHA_REQUEST_PARAMETER, '');

        return \count($this->validator->validate($this)) < 1;
    }

    
$loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata(Entity::class);
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new ConstraintB());
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addConstraint(new Traverse(false));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new Choice(['A', 'B']));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection(['fields' => [
            'foo' => [new NotNull()new Range(['min' => 3])],
            'bar' => [new Range(['min' => 5])],
        ]]));
        $expected->addPropertyConstraint('firstName', new Choice([
            'message' => 'Must be one of %choices%',
            'choices' => ['A', 'B'],
        ]));
$this->metadata = new ClassMetadata(self::TEST_CLASS);
        $this->metadataFactory = new FakeMetadataFactory();
        $this->metadataFactory->addMetadata($this->metadata);
        $this->guesser = new ValidatorTypeGuesser($this->metadataFactory);
    }

    /** * @dataProvider guessTypeProvider */
    public function testGuessType(Constraint $constraint, TypeGuess $guess)
    {
        $this->metadata->addPropertyConstraint(self::TEST_PROPERTY, $constraint);

        $this->assertEquals($guess$this->guesser->guessType(self::TEST_CLASS, self::TEST_PROPERTY));
    }

    public static function guessTypeProvider()
    {
        return [
            [new Type('array')new TypeGuess(CollectionType::class[], Guess::MEDIUM_CONFIDENCE)],
            [new Type('bool')new TypeGuess(CheckboxType::class[], Guess::MEDIUM_CONFIDENCE)],
            [new Type('boolean')new TypeGuess(CheckboxType::class[], Guess::MEDIUM_CONFIDENCE)],
            [new Type('double')new TypeGuess(NumberType::class[], Guess::MEDIUM_CONFIDENCE)],
            [
$this->metadata->addConstraint(new ClassCompositeConstraint([new PropertyConstraint()]));
    }

    public function testAddCompositeConstraintAcceptsNestedClassConstraints()
    {
        $this->metadata->addConstraint($constraint = new ClassCompositeConstraint([new ClassConstraint()]));
        $this->assertSame($this->metadata->getConstraints()[$constraint]);
    }

    public function testAddPropertyConstraints()
    {
        $this->metadata->addPropertyConstraint('firstName', new ConstraintA());
        $this->metadata->addPropertyConstraint('lastName', new ConstraintB());

        $this->assertEquals(['firstName', 'lastName']$this->metadata->getConstrainedProperties());
    }

    public function testAddMultiplePropertyConstraints()
    {
        $this->metadata->addPropertyConstraints('lastName', [new ConstraintA()new ConstraintB()]);

        $constraints = [
            new ConstraintA(['groups' => ['Default', 'Entity']]),
            
if (!$nullable && $type->isNullable()) {
                    $nullable = true;
                }
            }
            if (!$hasTypeConstraint) {
                if (1 === \count($builtinTypes)) {
                    if ($types[0]->isCollection() && \count($collectionValueType = $types[0]->getCollectionValueTypes()) > 0) {
                        [$collectionValueType] = $collectionValueType;
                        $this->handleAllConstraint($property$allConstraint$collectionValueType$metadata);
                    }

                    $metadata->addPropertyConstraint($property$this->getTypeConstraint($builtinTypes[0]$types[0]));
                } elseif ($scalar) {
                    $metadata->addPropertyConstraint($propertynew Type(['type' => 'scalar']));
                }
            }

            if (!$nullable && !$hasNotBlankConstraint && !$hasNotNullConstraint) {
                $metadata->addPropertyConstraint($propertynew NotNull());
            }
        }

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