Length example


    public $min;

    public function getDefaultOption(): ?string
    {
        return 'min';
    }

    protected function getConstraints(array $options): array
    {
        return [
            new Length(['min' => $options['min'] ?? null]),
        ];
    }
}


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

        return $loaded;
    }

    


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]));
    }
}
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]));
    }
}
$validator
            ->expects($this->once())
            ->method('startContext')
            ->willReturn($validatorContext);

        $validator->validate($entity, null, []);
    }

    public function testCollectionConstraintValidateAllGroupsForNestedConstraints()
    {
        $this->metadata->addPropertyConstraint('data', new Collection(['fields' => [
            'one' => [new NotBlank(['groups' => 'one'])new Length(['min' => 2, 'groups' => 'two'])],
            'two' => [new NotBlank(['groups' => 'two'])],
        ]]));

        $entity = new Entity();
        $entity->data = ['one' => 't', 'two' => ''];

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

        $this->assertCount(2, $violations);
        $this->assertInstanceOf(Length::class$violations->get(0)->getConstraint());
        $this->assertInstanceOf(NotBlank::class$violations->get(1)->getConstraint());
    }
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 LengthTest extends TestCase
{
    public function testNormalizerCanBeSet()
    {
        $length = new Length(['min' => 0, 'max' => 10, 'normalizer' => 'trim']);

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

    public function testInvalidNormalizerThrowsException()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).');
        new Length(['min' => 0, 'max' => 10, 'normalizer' => 'Unknown Callable']);
    }

    
$this->assertNoViolation();
    }
}

class DummyCompoundConstraint extends Compound
{
    protected function getConstraints(array $options): array
    {
        return [
            new NotBlank(),
            new Length(['max' => 3]),
        ];
    }
}
$this->assertCount(1, $violations);
        $this->assertSame('This value should not be blank.', $violations[0]->getMessage());
        $this->assertSame('data[field1]', $violations[0]->getPropertyPath());
    }

    public function testFieldsValidateInSequence()
    {
        $form = $this->formFactory->create(FormType::class, null, [
            'validation_groups' => new GroupSequence(['group1', 'group2']),
        ])
            ->add('foo', TextType::class[
                'constraints' => [new Length(['min' => 10, 'groups' => ['group1']])],
            ])
            ->add('bar', TextType::class[
                'constraints' => [new NotBlank(['groups' => ['group2']])],
            ])
        ;

        $form->submit(['foo' => 'invalid', 'bar' => null]);

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

        $this->assertCount(1, $errors);
        

    public function testValidCombinations($value$constraints)
    {
        $this->assertCount(0, Validation::createValidator()->validate($valuenew AtLeastOneOf($constraints)));
    }

    public static function getValidCombinations()
    {
        return [
            ['symfony', [
                new Length(['min' => 10]),
                new EqualTo(['value' => 'symfony']),
            ]],
            [150, [
                new Range(['min' => 10, 'max' => 20]),
                new GreaterThanOrEqual(['value' => 100]),
            ]],
            [7, [
                new LessThan(['value' => 5]),
                new IdenticalTo(['value' => 7]),
            ]],
            [-3, [
                
$this->createForm(['constraints' => ['foo' => 'bar']]);
    }

    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());
    }
class Foo2
{
    public function index()
    {
        $constraint1 = new Assert\Isbn('isbn10', 'custom Isbn message'); // no way to handle those arguments (not named, not in associative array).         $constraint2 = new Assert\Isbn([
            'type' => 'isbn10',
            'message' => 'custom Isbn message with options as array',
        ]);
        $constraint3 = new Assert\Isbn(message: 'custom Isbn message from named argument');
        $constraint4 = new Assert\Length(exactMessage: 'custom Length exact message from named argument');
        $constraint5 = new Assert\Length(exactMessage: 'custom Length exact message from named argument 1/2', minMessage: 'custom Length min message from named argument 2/2');
    }
}
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)
    {
        // add distracting constraint         $this->metadata->addPropertyConstraint(self::TEST_PROPERTY, new Email());

        


namespace Symfony\Component\Validator\Tests\Fixtures;

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

class EntityStaticCar extends EntityStaticVehicle
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('wheels', new Length(['max' => 99]));
    }
}
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class LengthValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator(): LengthValidator
    {
        return new LengthValidator();
    }

    public function testNullIsValid()
    {
        $this->validator->validate(null, new Length(['value' => 6]));

        $this->assertNoViolation();
    }

    public function testEmptyStringIsInvalid()
    {
        $this->validator->validate('', new Length([
            'value' => $limit = 6,
            'exactMessage' => 'myMessage',
        ]));

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

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