Skip to content

Commit

Permalink
Merge pull request #50 from LinioIT/fix/not-required-field-constraints
Browse files Browse the repository at this point in the history
Fix/not required field constraints
  • Loading branch information
klaussilveira authored Jul 31, 2020
2 parents dbdad6e + 3f6d2db commit 93e25d2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Node/BaseNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ public function walk($input)
protected function checkConstraints(string $field, $value): void
{
foreach ($this->constraints as $constraint) {
if (!$constraint->validate($value)) {
if (!$constraint->validate($value) && ($this->isRequired() || !empty($value))) {
throw new InvalidConstraintException($constraint->getErrorMessage($field));
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/Node/BaseNodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,19 @@ public function testIsGettingTransformedValue(): void
$child = $base->add('foobar', 'string', ['transformer' => new DateTimeTransformer()]);
$this->assertEquals(new \DateTime('2014-01-01 00:00:00'), $child->getValue('foobar', '2014-01-01 00:00:00'));
}

public function testNotRequiredWithConstraints(): void
{
$typeHandler = $this->prophesize(TypeHandler::class);
$typeHandler->getType('string')->willReturn(new BaseNode());

$base = new BaseNode();
$base->setTypeHandler($typeHandler->reveal());
$child = $base->add('foobar', 'string')
->setRequired(false)
->addConstraint(new StringSize(1, 255));

$this->assertNull($child->getValue('foobar', null));
$this->assertEmpty($child->getValue('foobar', ''));
}
}

0 comments on commit 93e25d2

Please sign in to comment.