1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace AppBundle\Form\Validation\Infrastructure; |
4
|
|
|
|
5
|
|
|
use AppBundle\Exception\HttpRuntimeException; |
6
|
|
|
use AppBundle\Form\Validation\EntityDoesNotExists; |
7
|
|
|
use Doctrine\ORM\EntityManager; |
8
|
|
|
use Doctrine\ORM\ORMException; |
9
|
|
|
use Symfony\Component\Validator\Constraint; |
10
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @author Vehsamrak |
14
|
|
|
*/ |
15
|
|
|
abstract class EntityValidator extends ConstraintValidator |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** @var EntityManager */ |
19
|
|
|
private $entityManager; |
20
|
|
|
|
21
|
|
|
public function __construct(EntityManager $entityManager) |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
$this->entityManager = $entityManager; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param string $entityFieldValue Entity field value |
28
|
|
|
* @param EntityDoesNotExists $constraint |
29
|
|
|
*/ |
30
|
|
|
public function findEntity($entityFieldValue, Constraint $constraint) |
31
|
|
|
{ |
32
|
|
|
try { |
33
|
|
|
$repository = $this->entityManager->getRepository($constraint->entityClass); |
34
|
|
|
} catch (ORMException $exception) { |
35
|
|
|
throw new HttpRuntimeException($exception->getMessage()); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$entity = $repository->findOneBy( |
39
|
|
|
[ |
40
|
|
|
$constraint->entityField => $entityFieldValue, |
41
|
|
|
] |
42
|
|
|
); |
43
|
|
|
|
44
|
|
|
return $entity; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @throws HttpRuntimeException |
49
|
|
|
*/ |
50
|
|
|
public function checkAnnotationParameters(EntityConstraint $constraint) |
51
|
|
|
{ |
52
|
|
|
if (empty($constraint->entityClass) || empty($constraint->entityField)) { |
53
|
|
|
throw new HttpRuntimeException('"entityClass" and "entityField" annotation parameters are mandatory.'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (!class_exists($constraint->entityClass)) { |
57
|
|
|
throw new HttpRuntimeException( |
58
|
|
|
sprintf('Class "%s" given in annotation does not exist.', $constraint->entityClass) |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
The
EntityManager
might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:If that code throws an exception and the
EntityManager
is closed. Any other code which depends on the same instance of theEntityManager
during this request will fail.On the other hand, if you instead inject the
ManagerRegistry
, thegetManager()
method guarantees that you will always get a usable manager instance.