Skip to content

Commit

Permalink
Skip validation if value is empty (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
aradoje authored Mar 2, 2020
1 parent 241f709 commit 6fc517a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
9 changes: 5 additions & 4 deletions src/EntityExistValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ public function __construct(EntityManagerInterface $entityManager)

public function validate($value, Constraint $constraint): void
{
if (empty($value)) {
return;
}

if (!$constraint instanceof EntityExist) {
throw new \LogicException(\sprintf(
'You can only pass %s constraint to this validator.',
EntityExist::class
));
throw new \LogicException(\sprintf('You can only pass %s constraint to this validator.', EntityExist::class));
}

if (empty($constraint->entity)) {
Expand Down
35 changes: 29 additions & 6 deletions tests/EntityExistValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,34 @@ public function testValidateWithNoEntity()
$this->validator->validate('foobar', $constraint);
}

public function testValidateValidEntity()
{
$this->context->expects($this->never())->method('buildViolation');
$constraint = new EntityExist();
$constraint->entity = 'App\Entity\User';

$repository = $this->getMockBuilder(EntityRepository::class)
->disableOriginalConstructor()
->getMock();
$repository
->expects($this->once())
->method('findOneBy')
->with(['id' => 'foobar'])
->willReturn('my_user');

$this->entityManager
->expects($this->once())
->method('getRepository')
->with('App\Entity\User')
->willReturn($repository);

$this->validator->validate('foobar', $constraint);
}

/**
* @dataProvider getValidValues
* @dataProvider getEmptyOrNull
*/
public function testValidateValidEntity($value)
public function testValidateSkipsIfValueEmptyOrNull($value)
{
$this->context->expects($this->never())->method('buildViolation');
$constraint = new EntityExist();
Expand All @@ -61,23 +85,22 @@ public function testValidateValidEntity($value)
->disableOriginalConstructor()
->getMock();
$repository
->expects($this->once())
->expects($this->exactly(0))
->method('findOneBy')
->with(['id' => $value])
->willReturn('my_user');

$this->entityManager
->expects($this->once())
->expects($this->exactly(0))
->method('getRepository')
->with('App\Entity\User')
->willReturn($repository);

$this->validator->validate($value, $constraint);
}

public function getValidValues()
public function getEmptyOrNull()
{
yield ['foobar'];
yield [''];
yield [null];
}
Expand Down

0 comments on commit 6fc517a

Please sign in to comment.