1 | <?php |
||||
2 | |||||
3 | declare(strict_types=1); |
||||
4 | |||||
5 | namespace Happyr\Validator\Constraint; |
||||
6 | |||||
7 | use Doctrine\ORM\EntityManagerInterface; |
||||
8 | use Symfony\Component\Validator\Constraint; |
||||
9 | use Symfony\Component\Validator\ConstraintValidator; |
||||
10 | |||||
11 | /** |
||||
12 | * @author Tobias Nyholm <[email protected]> |
||||
13 | * @author Radoje Albijanic <[email protected]> |
||||
14 | */ |
||||
15 | final class EntityExistValidator extends ConstraintValidator |
||||
16 | { |
||||
17 | private $entityManager; |
||||
18 | |||||
19 | 7 | public function __construct(EntityManagerInterface $entityManager) |
|||
20 | { |
||||
21 | 7 | $this->entityManager = $entityManager; |
|||
22 | 7 | } |
|||
23 | |||||
24 | 7 | public function validate($value, Constraint $constraint): void |
|||
25 | { |
||||
26 | 7 | if (!$constraint instanceof EntityExist) { |
|||
27 | 2 | throw new \LogicException(\sprintf('You can only pass %s constraint to this validator.', EntityExist::class)); |
|||
28 | } |
||||
29 | |||||
30 | 5 | if (null === $value || '' === $value) { |
|||
31 | 1 | return; |
|||
32 | } |
||||
33 | |||||
34 | 4 | if (empty($constraint->entity)) { |
|||
35 | 1 | throw new \LogicException(\sprintf('Must set "entity" on "%s" validator', EntityExist::class)); |
|||
36 | } |
||||
37 | |||||
38 | 3 | $data = $this->entityManager->getRepository($constraint->entity)->findOneBy([ |
|||
39 | 3 | $constraint->property => $value, |
|||
40 | ]); |
||||
41 | |||||
42 | 3 | if (null === $data) { |
|||
43 | 1 | $this->context->buildViolation($constraint->message) |
|||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||||
44 | 1 | ->setParameter('%entity%', $constraint->entity) |
|||
0 ignored issues
–
show
It seems like
$constraint->entity can also be of type mixed ; however, parameter $value of Symfony\Component\Valida...terface::setParameter() does only seem to accept string , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||
45 | 1 | ->setParameter('%property%', $constraint->property) |
|||
46 | 1 | ->setParameter('%value%', (string) $value) |
|||
47 | 1 | ->addViolation(); |
|||
48 | } |
||||
49 | 3 | } |
|||
50 | } |
||||
51 |