NotNull example

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

    private function getTypeConstraint(string $builtinType, PropertyInfoType $type): Type
    {
        if (PropertyInfoType::BUILTIN_TYPE_OBJECT === $builtinType && null !== $className = $type->getClassName()) {
            return new Type(['type' => $className]);
        }

        

        ];

        $this->assertEquals($expected$normalizer->normalize($list));
    }

    /** * @dataProvider payloadFieldsProvider */
    public function testNormalizePayloadFields($fields, array $expected = null)
    {
        $constraint = new NotNull();
        $constraint->payload = ['severity' => 'warning', 'anotherField2' => 'aValue'];
        $list = new ConstraintViolationList([
            new ConstraintViolation('a', 'b', [], 'c', 'd', 'e', null, null, $constraint),
        ]);

        $violation = $this->normalizer->normalize($list, null, [ConstraintViolationListNormalizer::PAYLOAD_FIELDS => $fields])['violations'][0];
        if ([] === $fields) {
            $this->assertArrayNotHasKey('payload', $violation);

            return;
        }
        
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\When;

#[When(expression: 'true', constraints: [     new Callback('callback'),
])]
class WhenTestWithAttributes
{
    #[When(expression: 'true', constraints: [         new NotNull(),
        new NotBlank(),
    ])]
    private $foo;

    #[When(expression: 'false', constraints: [         new NotNull(),
        new NotBlank(),
    ], groups: ['foo'])]
    private $bar;

    #[When(expression: 'true', constraints: new NotNull(), groups: ['foo'])]
new Callback([
                'callback' => 'callback',
                'groups' => ['Default', 'WhenTestWithAnnotations'],
            ]),
        ]$classConstraint->constraints);

        [$fooConstraint] = $metadata->properties['foo']->getConstraints();

        self::assertInstanceOf(When::class$fooConstraint);
        self::assertSame('true', $fooConstraint->expression);
        self::assertEquals([
            new NotNull([
                'groups' => ['Default', 'WhenTestWithAnnotations'],
            ]),
            new NotBlank([
                'groups' => ['Default', 'WhenTestWithAnnotations'],
            ]),
        ]$fooConstraint->constraints);
        self::assertSame(['Default', 'WhenTestWithAnnotations']$fooConstraint->groups);

        [$barConstraint] = $metadata->properties['bar']->getConstraints();

        self::assertInstanceOf(When::class$fooConstraint);
        
protected function setUp(): void
    {
        $this->group = 'MyGroup';
        $this->metadata = null;
        $this->object = null;
        $this->value = 'InvalidValue';
        $this->root = 'root';
        $this->propertyPath = 'property.path';

        // Initialize the context with some constraint so that we can         // successfully build a violation.         $this->constraint = new NotNull();

        $this->context = $this->createContext();
        $this->validator = $this->createValidator();
        $this->validator->initialize($this->context);

        $this->defaultLocale = \Locale::getDefault();
        \Locale::setDefault('en');

        $this->expectedViolations = [];
        $this->call = 0;

        
new Type('long')new TypeGuess(IntegerType::class[], Guess::MEDIUM_CONFIDENCE)],
            [new Type('string')new TypeGuess(TextType::class[], Guess::LOW_CONFIDENCE)],
            [new Type(\DateTime::class)new TypeGuess(DateType::class[], Guess::MEDIUM_CONFIDENCE)],
            [new Type(\DateTimeImmutable::class)new TypeGuess(DateType::class['input' => 'datetime_immutable'], Guess::MEDIUM_CONFIDENCE)],
            [new Type('\DateTime')new TypeGuess(DateType::class[], Guess::MEDIUM_CONFIDENCE)],
        ];
    }

    public static function guessRequiredProvider()
    {
        return [
            [new NotNull()new ValueGuess(true, Guess::HIGH_CONFIDENCE)],
            [new NotBlank()new ValueGuess(true, Guess::HIGH_CONFIDENCE)],
            [new IsTrue()new ValueGuess(true, Guess::HIGH_CONFIDENCE)],
            [new Length(['min' => 10, 'max' => 10])new ValueGuess(false, Guess::LOW_CONFIDENCE)],
            [new Range(['min' => 1, 'max' => 20])new ValueGuess(false, Guess::LOW_CONFIDENCE)],
        ];
    }

    /** * @dataProvider guessRequiredProvider */
    public function testGuessRequired($constraint$guess)
    {
$this->validator->validate($arraynew All($constraint));

        $this->assertNoViolation();
    }

    /** * @dataProvider getValidArguments */
    public function testWalkMultipleConstraints($array)
    {
        $constraint1 = new Range(['min' => 4]);
        $constraint2 = new NotNull();

        $constraints = [$constraint1$constraint2];

        $i = 0;

        foreach ($array as $key => $value) {
            $this->expectValidateValueAt($i++, '['.$key.']', $value[$constraint1$constraint2]);
        }

        $this->validator->validate($arraynew All($constraints));

        
$metadata = new ClassMetadata(Entity::class);

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

    private function getTypeConstraint(string $builtinType, PropertyInfoType $type): Type
    {
        if (PropertyInfoType::BUILTIN_TYPE_OBJECT === $builtinType && null !== $className = $type->getClassName()) {
            return new Type(['type' => $className]);
        }

        
class ConstraintValidatorTestCaseTest extends ConstraintValidatorTestCase
{
    protected function createValidator(): TestCustomValidator
    {
        return new TestCustomValidator();
    }

    public function testAssertingContextualValidatorRemainingExpectationsThrow()
    {
        $this->expectValidateValueAt(0, 'k1', 'ccc', [
            new NotNull(),
        ]);
        $this->expectValidateValueAt(1, 'k2', 'ccc', [
            new DateTime(),
        ]);

        $this->validator->validate('ccc', $this->constraint);

        $contextualValidator = $this->context->getValidator()->inContext($this->context);
        // Simulate __destruct to assert it throws         try {
            $contextualValidator->__destruct();
            
public function testEmptyStringIsValid()
    {
        $this->validator->validate('', new Cidr());

        $this->assertNoViolation();
    }

    public function testInvalidConstraint()
    {
        $this->expectException(UnexpectedTypeException::class);

        $this->validator->validate('neko', new NotNull());
    }

    public function testExpectsStringCompatibleType()
    {
        $this->expectException(UnexpectedValueException::class);

        $this->validator->validate(123456, new Cidr());
    }

    /** * @dataProvider getWithInvalidNetmask */
use Symfony\Component\Validator\Constraints\PositiveOrZero;
use Symfony\Component\Validator\Constraints\When;
use Symfony\Component\Validator\Constraints\WhenValidator;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

final class WhenValidatorTest extends ConstraintValidatorTestCase
{
    public function testConstraintsAreExecuted()
    {
        $constraints = [
            new NotNull(),
            new NotBlank(),
        ];

        $this->expectValidateValue(0, 'Foo', $constraints);

        $this->validator->validate('Foo', new When([
            'expression' => 'true',
            'constraints' => $constraints,
        ]));
    }

    
$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->expectValidateAt(0, 'data', $object['group1', 'group2']);

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

        $this->assertNoViolation();
    }

    public function testValidateConstraints()
    {
        $object = new \stdClass();
        $constraint1 = new NotNull(['groups' => ['group1', 'group2']]);
        $constraint2 = new NotBlank(['groups' => 'group2']);
        $constraint3 = new Length(['groups' => 'group2', 'min' => 3]);

        $options = [
            'validation_groups' => ['group1', 'group2'],
            'constraints' => [$constraint1$constraint2$constraint3],
        ];
        $form = $this->getCompoundForm($object$options);
        $form->submit([]);

        // First default constraints
Assert\Callback([CallbackClass::class, 'callback']),
    Assert\Sequentially([
        new Assert\Expression('this.getFirstName() != null')
    ])
]
class Entity extends EntityParent implements EntityInterfaceB
{
    #[         Assert\NotNull,
        Assert\Range(min: 3),
        Assert\All([
            new Assert\NotNull(),
            new Assert\Range(min: 3),
        ]),
        Assert\All(
            constraints: [
                new Assert\NotNull(),
                new Assert\Range(min: 3),
            ],
        ),
        Assert\Collection(
            fields: [
                'foo' => [
                    
Home | Imprint | This part of the site doesn't use cookies.