Skip to content

Commit 6fc517a

Browse files
authored
Skip validation if value is empty (#4)
1 parent 241f709 commit 6fc517a

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

src/EntityExistValidator.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,12 @@ public function __construct(EntityManagerInterface $entityManager)
2323

2424
public function validate($value, Constraint $constraint): void
2525
{
26+
if (empty($value)) {
27+
return;
28+
}
29+
2630
if (!$constraint instanceof EntityExist) {
27-
throw new \LogicException(\sprintf(
28-
'You can only pass %s constraint to this validator.',
29-
EntityExist::class
30-
));
31+
throw new \LogicException(\sprintf('You can only pass %s constraint to this validator.', EntityExist::class));
3132
}
3233

3334
if (empty($constraint->entity)) {

tests/EntityExistValidatorTest.php

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,34 @@ public function testValidateWithNoEntity()
4848
$this->validator->validate('foobar', $constraint);
4949
}
5050

51+
public function testValidateValidEntity()
52+
{
53+
$this->context->expects($this->never())->method('buildViolation');
54+
$constraint = new EntityExist();
55+
$constraint->entity = 'App\Entity\User';
56+
57+
$repository = $this->getMockBuilder(EntityRepository::class)
58+
->disableOriginalConstructor()
59+
->getMock();
60+
$repository
61+
->expects($this->once())
62+
->method('findOneBy')
63+
->with(['id' => 'foobar'])
64+
->willReturn('my_user');
65+
66+
$this->entityManager
67+
->expects($this->once())
68+
->method('getRepository')
69+
->with('App\Entity\User')
70+
->willReturn($repository);
71+
72+
$this->validator->validate('foobar', $constraint);
73+
}
74+
5175
/**
52-
* @dataProvider getValidValues
76+
* @dataProvider getEmptyOrNull
5377
*/
54-
public function testValidateValidEntity($value)
78+
public function testValidateSkipsIfValueEmptyOrNull($value)
5579
{
5680
$this->context->expects($this->never())->method('buildViolation');
5781
$constraint = new EntityExist();
@@ -61,23 +85,22 @@ public function testValidateValidEntity($value)
6185
->disableOriginalConstructor()
6286
->getMock();
6387
$repository
64-
->expects($this->once())
88+
->expects($this->exactly(0))
6589
->method('findOneBy')
6690
->with(['id' => $value])
6791
->willReturn('my_user');
6892

6993
$this->entityManager
70-
->expects($this->once())
94+
->expects($this->exactly(0))
7195
->method('getRepository')
7296
->with('App\Entity\User')
7397
->willReturn($repository);
7498

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

78-
public function getValidValues()
102+
public function getEmptyOrNull()
79103
{
80-
yield ['foobar'];
81104
yield [''];
82105
yield [null];
83106
}

0 commit comments

Comments
 (0)