Merge pull request #1781 from chrisguitarguy/fix_lengths

Check Min and Max in Length Constraints Before Setting in Schemas
This commit is contained in:
Guilhem Niot 2021-02-16 01:03:59 +01:00 committed by GitHub
commit ceda09fe85
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 2 deletions

View File

@ -69,8 +69,12 @@ class SymfonyConstraintAnnotationReader
$this->schema->required = array_values(array_unique($existingRequiredFields));
} elseif ($annotation instanceof Assert\Length) {
$property->minLength = (int) $annotation->min;
$property->maxLength = (int) $annotation->max;
if (isset($annotation->min)) {
$property->minLength = (int) $annotation->min;
}
if (isset($annotation->max)) {
$property->maxLength = (int) $annotation->max;
}
} elseif ($annotation instanceof Assert\Regex) {
$this->appendPattern($property, $annotation->getHtmlPattern());
} elseif ($annotation instanceof Assert\Count) {

View File

@ -105,4 +105,52 @@ class SymfonyConstraintAnnotationReaderTest extends TestCase
// expect enum to be numeric array with sequential keys (not [1 => "active", 2 => "active"])
$this->assertEquals($schema->properties[0]->enum, ['active', 'blocked']);
}
/**
* @group https://github.com/nelmio/NelmioApiDocBundle/issues/1780
*/
public function testLengthConstraintDoesNotSetMaxLengthIfMaxIsNotSet()
{
$entity = new class() {
/**
* @Assert\Length(min = 1)
*/
private $property1;
};
$schema = new OA\Schema([]);
$schema->merge([new OA\Property(['property' => 'property1'])]);
$symfonyConstraintAnnotationReader = new SymfonyConstraintAnnotationReader(new AnnotationReader());
$symfonyConstraintAnnotationReader->setSchema($schema);
$symfonyConstraintAnnotationReader->updateProperty(new \ReflectionProperty($entity, 'property1'), $schema->properties[0]);
$this->assertSame(OA\UNDEFINED, $schema->properties[0]->maxLength);
$this->assertSame(1, $schema->properties[0]->minLength);
}
/**
* @group https://github.com/nelmio/NelmioApiDocBundle/issues/1780
*/
public function testLengthConstraintDoesNotSetMinLengthIfMinIsNotSet()
{
$entity = new class() {
/**
* @Assert\Length(max = 100)
*/
private $property1;
};
$schema = new OA\Schema([]);
$schema->merge([new OA\Property(['property' => 'property1'])]);
$symfonyConstraintAnnotationReader = new SymfonyConstraintAnnotationReader(new AnnotationReader());
$symfonyConstraintAnnotationReader->setSchema($schema);
$symfonyConstraintAnnotationReader->updateProperty(new \ReflectionProperty($entity, 'property1'), $schema->properties[0]);
$this->assertSame(OA\UNDEFINED, $schema->properties[0]->minLength);
$this->assertSame(100, $schema->properties[0]->maxLength);
}
}