diff --git a/src/Node/BaseNode.php b/src/Node/BaseNode.php index 580c50e..2e05f1a 100644 --- a/src/Node/BaseNode.php +++ b/src/Node/BaseNode.php @@ -275,12 +275,17 @@ public function walk($input) protected function checkConstraints(string $field, $value): void { foreach ($this->constraints as $constraint) { - if (!$constraint->validate($value) && ($this->isRequired() || !empty($value))) { + if (!$constraint->validate($value) && ($this->isRequired() || $this->checkIfFieldValueIsSpecified($value))) { throw new InvalidConstraintException($constraint->getErrorMessage($field)); } } } + private function checkIfFieldValueIsSpecified($value): bool + { + return $this->type === 'string' || $this->type === 'array' ? !empty($value) : $value !== null; + } + private function setHandler(InputHandler $handler, string $type): self { $handler->setRootType($type); diff --git a/tests/Node/BaseNodeTest.php b/tests/Node/BaseNodeTest.php index 0e7887c..b238e4e 100644 --- a/tests/Node/BaseNodeTest.php +++ b/tests/Node/BaseNodeTest.php @@ -5,6 +5,7 @@ namespace Linio\Component\Input\Node; use Linio\Component\Input\Constraint\NotNull; +use Linio\Component\Input\Constraint\Range; use Linio\Component\Input\Constraint\StringSize; use Linio\Component\Input\Exception\InvalidConstraintException; use Linio\Component\Input\Transformer\DateTimeTransformer; @@ -142,6 +143,25 @@ public function testNotRequiredWithConstraints(): void ->addConstraint(new StringSize(1, 255)); $this->assertNull($child->getValue('foobar', null)); - $this->assertEmpty($child->getValue('foobar', '')); + } + + public function testNotRequiredWithContraintsAndIntegerField(): void + { + $typeHandler = $this->prophesize(TypeHandler::class); + $typeHandler->getType('integer')->willReturn(new BaseNode()); + + $base = new BaseNode(); + $base->setTypeHandler($typeHandler->reveal()); + $base->setTypeAlias('integer'); + $child = $base->add('foobar', 'integer') + ->setTypeAlias('integer') + ->setRequired(false) + ->addConstraint(new Range(1, 255)) + ->setType('integer'); + + $this->assertEmpty($child->getValue('foobar', null)); + + $this->expectException(InvalidConstraintException::class); + $child->getValue('foobar', 0); } }