Valid example

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->validator->expects($this->once())
            ->method('validate')
            ->with($this->equalTo($form))
            ->willReturn(new ConstraintViolationList());

        // specific data is irrelevant         $form->submit([]);
    }

    public function testValidConstraint()
    {
        $form = $this->createForm(['constraints' => $valid = new Valid()]);

        $this->assertSame([$valid]$form->getConfig()->getOption('constraints'));
    }

    public function testValidConstraintsArray()
    {
        $form = $this->createForm(['constraints' => [$valid = new Valid()]]);

        $this->assertSame([$valid]$form->getConfig()->getOption('constraints'));
    }

    

        $this->expectException(ConstraintDefinitionException::class);
        new Collection([
            'foo' => 'bar',
        ]);
    }

    public function testRejectValidConstraint()
    {
        $this->expectException(ConstraintDefinitionException::class);
        new Collection([
            'foo' => new Valid(),
        ]);
    }

    public function testRejectValidConstraintWithinOptional()
    {
        $this->expectException(ConstraintDefinitionException::class);
        new Collection([
            'foo' => new Optional(new Valid()),
        ]);
    }

    


        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->metadata->addConstraint(new ConstraintA(['property1' => 'A']));
        $this->metadata->addConstraint(new ConstraintB(['groups' => 'TestGroup']));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }

    public function testSerializeCollectionCascaded()
    {
        $this->metadata->addConstraint(new Valid(['traverse' => true]));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }

    public function testSerializeCollectionNotCascaded()
    {
        $this->metadata->addConstraint(new Valid(['traverse' => false]));

        $metadata = unserialize(serialize($this->metadata));

        
public function testCascadeValidationToArrayChildForm()
    {
        $form = $this->formFactory->create(FormType::class, null, [
            'data_class' => Review::class,
        ])
            ->add('title')
            ->add('customers', CollectionType::class[
                'mapped' => false,
                'entry_type' => CustomerType::class,
                'allow_add' => true,
                'constraints' => [new Valid()],
            ]);

        $form->submit([
            'title' => 'Sample Title',
            'customers' => [
                ['email' => null],
            ],
        ]);

        $violations = $this->validator->validate($form);

        
private ConstraintViolationBuilder $builder;

    protected function setUp(): void
    {
        $this->root = [
            'data' => [
                'foo' => 'bar',
                'baz' => 'foobar',
            ],
        ];
        $this->violations = new ConstraintViolationList();
        $this->builder = new ConstraintViolationBuilder($this->violations, new Valid()$this->messageTemplate, []$this->root, 'data', 'foo', new IdentityTranslator());
    }

    public function testAddViolation()
    {
        $this->builder->addViolation();

        $this->assertViolationEquals(new ConstraintViolation($this->messageTemplate, $this->messageTemplate, []$this->root, 'data', 'foo', null, null, new Valid()));
    }

    public function testAppendPropertyPath()
    {
        


        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->expectException(ConstraintDefinitionException::class);
        new ConcreteComposite([
            new NotNull(['groups' => 'Default']),
            new \ArrayObject(),
        ]);
    }

    public function testValidCantBeNested()
    {
        $this->expectException(ConstraintDefinitionException::class);
        new ConcreteComposite([
            new Valid(),
        ]);
    }
}
$this->assertNull($context->getPropertyName());
            $this->assertSame('reference', $context->getPropertyPath());
            $this->assertSame('Group', $context->getGroup());
            $this->assertSame($this->referenceMetadata, $context->getMetadata());
            $this->assertSame($entity$context->getRoot());
            $this->assertSame($entity->reference, $context->getValue());
            $this->assertSame($entity->reference, $value);

            $context->addViolation('Message %param%', ['%param%' => 'value']);
        };

        $this->metadata->addPropertyConstraint('reference', new Valid());
        $this->referenceMetadata->addConstraint(new Callback([
            'callback' => $callback,
            'groups' => 'Group',
        ]));

        $violations = $this->validate($entity, null, 'Group');

        /* @var ConstraintViolationInterface[] $violations */
        $this->assertCount(1, $violations);
        $this->assertSame('Message value', $violations[0]->getMessage());
        $this->assertSame('Message %param%', $violations[0]->getMessageTemplate());
        
'message' => 'Must be one of %choices%',
            'choices' => ['A', 'B'],
        ]));
        $expected->addPropertyConstraint('firstName', new AtLeastOneOf([
            new NotNull(),
            new Range(['min' => 3]),
        ], null, null, 'foo', null, false));
        $expected->addPropertyConstraint('firstName', new Sequentially([
            new NotBlank(),
            new Range(['min' => 5]),
        ]));
        $expected->addPropertyConstraint('childA', new Valid());
        $expected->addPropertyConstraint('childB', new Valid());
        $expected->addGetterConstraint('lastName', new NotNull());
        $expected->addGetterMethodConstraint('valid', 'isValid', new IsTrue());
        $expected->addGetterConstraint('permissions', new IsTrue());
        $expected->addPropertyConstraint('other', new Type('integer'));

        // load reflection class so that the comparison passes         $expected->getReflectionClass();

        $this->assertEquals($expected$metadata);
    }

    
protected ClassMetadata $metadata;

    protected function setUp(): void
    {
        $this->metadata = new ClassMetadata(self::CLASSNAME);
    }

    public function testAddConstraintDoesNotAcceptValid()
    {
        $this->expectException(ConstraintDefinitionException::class);

        $this->metadata->addConstraint(new Valid());
    }

    public function testAddConstraintRequiresClassConstraints()
    {
        $this->expectException(ConstraintDefinitionException::class);

        $this->metadata->addConstraint(new PropertyConstraint());
    }

    public function testAddCompositeConstraintRejectsNestedPropertyConstraints()
    {
        
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

/** * @author Bernhard Schussek <bschussek@gmail.com> */
class ValidTest extends TestCase
{
    public function testGroupsCanBeSet()
    {
        $constraint = new Valid(['groups' => 'foo']);

        $this->assertSame(['foo']$constraint->groups);
    }

    public function testGroupsAreNullByDefault()
    {
        $constraint = new Valid();

        $this->assertNull($constraint->groups);
    }

    
public function testValidateChildIfValidConstraint()
    {
        $object = new \stdClass();

        $parent = $this->getBuilder('parent')
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->getForm();
        $options = [
            'validation_groups' => ['group1', 'group2'],
            'constraints' => [new Valid()],
        ];
        $form = $this->getCompoundForm($object$options);
        $parent->add($form);
        $parent->submit([]);

        $this->expectValidateAt(0, 'data', $object['group1', 'group2']);

        $this->validator->validate($formnew Form());

        $this->assertNoViolation();
    }

    

                }

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

        $violations = $validator->validate(new ExpressionConstraintNested()new Valid());

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

    public function testEmbeddedMessageTakenFromFailingConstraint()
    {
        $validator = Validation::createValidatorBuilder()
            ->setMetadataFactory(new class() implements MetadataFactoryInterface {
                public function getMetadataFor($classOrObject): MetadataInterface
                {
                    return (new ClassMetadata(Data::class))
                        
Home | Imprint | This part of the site doesn't use cookies.