NotBlank example

use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\ValidationFailedException;
use Symfony\Component\Validator\Validation;

/** * @author Jan Vernieuwe <jan.vernieuwe@phpro.be> */
class ValidationTest extends TestCase
{
    public function testCreateCallableValid()
    {
        $validator = Validation::createCallable(new NotBlank());
        $this->assertEquals('test@example.com', $validator('test@example.com'));
    }

    public function testCreateCallableInvalid()
    {
        $validator = Validation::createCallable(new Blank());
        try {
            $validator('test');
            $this->fail('No ValidationFailedException thrown');
        } catch (ValidationFailedException $e) {
            $this->assertEquals('test', $e->getValue());

            

    protected function createValidator(): NotBlankValidator
    {
        return new NotBlankValidator();
    }

    /** * @dataProvider getValidValues */
    public function testValidValues($value)
    {
        $this->validator->validate($valuenew NotBlank());

        $this->assertNoViolation();
    }

    public static function getValidValues()
    {
        return [
            ['foobar'],
            [0],
            [0.0],
            ['0'],
            [
$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         $this->expectValidateAt(0, 'data', $object['group1', 'group2']);

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

    public function testConstraintIsExecuted()
    {
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'])]     private $qux;

    

        $expected->addConstraint(new Callback(['callback' => 'validateMe', 'payload' => 'foo']));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $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([
            'foo' => [new NotNull()new Range(['min' => 3])],
            'bar' => new Range(['min' => 5]),
            'baz' => new Required([new Email()]),
            'qux' => new Optional([new NotBlank()]),
        ], null, null, true));
        $expected->addPropertyConstraint('firstName', new Choice([
            '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(),
            
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

/** * @author Renan Taranto <renantaranto@gmail.com> */
class NotBlankTest extends TestCase
{
    public function testNormalizerCanBeSet()
    {
        $notBlank = new NotBlank(['normalizer' => 'trim']);

        $this->assertEquals('trim', $notBlank->normalizer);
    }

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

        [$aConstraint] = $metadata->properties['a']->getConstraints();
        
use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;

class CompoundTest extends TestCase
{
    public function testItCannotRedefineConstraintsOption()
    {
        $this->expectException(ConstraintDefinitionException::class);
        $this->expectExceptionMessage('You can\'t redefine the "constraints" option. Use the "Symfony\Component\Validator\Constraints\Compound::getConstraints()" method instead.');
        new EmptyCompound(['constraints' => [new NotBlank()]]);
    }

    public function testCanDependOnNormalizedOptions()
    {
        $constraint = new ForwardingOptionCompound($min = 3);

        $this->assertSame($min$constraint->constraints[0]->min);
    }
}

class EmptyCompound extends Compound
{
new Assert\Range(min: 3),
            ],
        ),
        Assert\Collection(
            fields: [
                'foo' => [
                    new Assert\NotNull(),
                    new Assert\Range(min: 3),
                ],
                'bar' => new Assert\Range(min: 5),
                'baz' => new Assert\Required([new Assert\Email()]),
                'qux' => new Assert\Optional([new Assert\NotBlank()]),
            ],
            allowExtraFields: true
        ),
        Assert\Choice(choices: ['A', 'B'], message: 'Must be one of %choices%'),
        Assert\AtLeastOneOf(
            constraints: [
                new Assert\NotNull(),
                new Assert\Range(min: 3),
            ],
            message: 'foo',
            includeInternalMessages: false,
        ),

        ]$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);
        self::assertSame('false', $barConstraint->expression);
        self::assertEquals([
            new NotNull([
                

  protected static function validateAdvisoryData(array $data): void {
    $not_blank_constraints = [
      new Type(['type' => 'string']),
      new NotBlank(),
    ];
    $collection_constraint = new Collection([
      'fields' => [
        'title' => $not_blank_constraints,
        'project' => $not_blank_constraints,
        'type' => $not_blank_constraints,
        'link' => $not_blank_constraints,
        'is_psa' => new Choice(['choices' => [1, '1', 0, '0', TRUE, FALSE]]),
        'insecure' => new Type(['type' => 'array']),
      ],
      // Allow unknown fields, in the case that new fields are added to JSON
$this->assertSame($constraint$violations[0]->getConstraint());
    }

    public function testNestedObjectIsNotValidatedIfGroupInValidConstraintIsNotValidated()
    {
        $entity = new Entity();
        $entity->firstName = '';
        $reference = new Reference();
        $reference->value = '';
        $entity->childA = $reference;

        $this->metadata->addPropertyConstraint('firstName', new NotBlank(['groups' => 'group1']));
        $this->metadata->addPropertyConstraint('childA', new Valid(['groups' => 'group1']));
        $this->referenceMetadata->addPropertyConstraint('value', new NotBlank());

        $violations = $this->validator->validate($entity, null, []);

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

    public function testNestedObjectIsValidatedIfGroupInValidConstraintIsValidated()
    {
        $entity = new Entity();
        
$metadata->addConstraint(new ConstraintA());

        return true;
    }
}

class PropertyGetterInterfaceConstraintLoader implements LoaderInterface
{
    public function loadClassMetadata(ClassMetadata $metadata): bool
    {
        if (PropertyGetterInterface::class === $metadata->getClassName()) {
            $metadata->addGetterConstraint('property', new NotBlank());
        }

        return true;
    }
}


/** * @author Bernhard Schussek <bschussek@gmail.com> */
class CompositeTest extends TestCase
{
    public function testConstraintHasDefaultGroup()
    {
        $constraint = new ConcreteComposite([
            new NotNull(),
            new NotBlank(),
        ]);

        $this->assertEquals(['Default']$constraint->groups);
        $this->assertEquals(['Default']$constraint->constraints[0]->groups);
        $this->assertEquals(['Default']$constraint->constraints[1]->groups);
    }

    public function testNestedCompositeConstraintHasDefaultGroup()
    {
        $constraint = new ConcreteComposite([
            new ConcreteComposite(),
            


    public function testGroupSequenceWithConstraintsOption()
    {
        $form = Forms::createFormFactoryBuilder()
            ->addExtension(new ValidatorExtension(Validation::createValidator(), false))
            ->getFormFactory()
            ->create(FormTypeTest::TESTED_TYPE, null, ['validation_groups' => new GroupSequence(['First', 'Second'])])
            ->add('field', TextTypeTest::TESTED_TYPE, [
                'constraints' => [
                    new Length(['min' => 10, 'groups' => ['First']]),
                    new NotBlank(['groups' => ['Second']]),
                ],
            ])
        ;

        $form->submit(['field' => 'wrong']);

        $errors = $form->getErrors(true);

        $this->assertCount(1, $errors);
        $this->assertInstanceOf(Length::class$errors[0]->getCause()->getConstraint());
    }

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