Skip to content

Commit

Permalink
Merge pull request #51 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 Aug 5, 2020
2 parents 93e25d2 + 9b4f98d commit e52fb3c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/Node/BaseNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
22 changes: 21 additions & 1 deletion tests/Node/BaseNodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

0 comments on commit e52fb3c

Please sign in to comment.