From 0da1909cb9aa42174dccdb06edc2a9bb17fb92da Mon Sep 17 00:00:00 2001 From: Alex Kalineskou Date: Mon, 31 Aug 2020 23:22:42 +0300 Subject: [PATCH] Add support for allowNull for Assert\NotBlank --- .../SymfonyConstraintAnnotationReader.php | 5 ++++ .../SymfonyConstraintAnnotationReaderTest.php | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php b/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php index 6143672..311bebe 100644 --- a/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php +++ b/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php @@ -48,6 +48,11 @@ class SymfonyConstraintAnnotationReader foreach ($annotations as $annotation) { if ($annotation instanceof Assert\NotBlank || $annotation instanceof Assert\NotNull) { + if ($annotation instanceof Assert\NotBlank && $annotation->allowNull) { + // The field is optional + continue; + } + // The field is required if (null === $this->schema) { continue; diff --git a/Tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php b/Tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php index 55ea9ec..e30cb49 100644 --- a/Tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php +++ b/Tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php @@ -47,6 +47,34 @@ class SymfonyConstraintAnnotationReaderTest extends TestCase $this->assertEquals($schema->getRequired(), ['property1', 'property2']); } + public function testOptionalProperty() + { + $entity = new class() { + /** + * @Assert\NotBlank(allowNull = true) + * @Assert\Length(min = 1) + */ + private $property1; + /** + * @Assert\NotBlank() + */ + private $property2; + }; + + $schema = new OA\Schema([]); + $schema->merge([new OA\Property(['property' => 'property1'])]); + $schema->merge([new OA\Property(['property' => 'property2'])]); + + $symfonyConstraintAnnotationReader = new SymfonyConstraintAnnotationReader(new AnnotationReader()); + $symfonyConstraintAnnotationReader->setSchema($schema); + + $symfonyConstraintAnnotationReader->updateProperty(new \ReflectionProperty($entity, 'property1'), $schema->properties[0]); + $symfonyConstraintAnnotationReader->updateProperty(new \ReflectionProperty($entity, 'property2'), $schema->properties[1]); + + // expect required to be numeric array with sequential keys (not [0 => ..., 2 => ...]) + $this->assertEquals($schema->required, ['property2']); + } + public function testAssertChoiceResultsInNumericArray() { define('TEST_ASSERT_CHOICE_STATUSES', [