1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare (strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace HMLB\DDDBundle\Validator\Constraint; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\Persistence\ObjectManager; |
8
|
|
|
use Doctrine\Common\Persistence\ObjectRepository; |
9
|
|
|
use HMLB\DDD\Entity\Identity; |
10
|
|
|
use Symfony\Component\Validator\Constraint; |
11
|
|
|
use Symfony\Component\Validator\ConstraintValidator; |
12
|
|
|
use Symfony\Component\Validator\Exception\ConstraintDefinitionException; |
13
|
|
|
use Symfony\Component\Validator\Exception\UnexpectedTypeException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* ExistingAggregateRootValidator. |
17
|
|
|
* |
18
|
|
|
* @author Hugues Maignol <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class ExistingAggregateRootValidator extends ConstraintValidator |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var ObjectManager |
24
|
|
|
*/ |
25
|
|
|
private $om; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* ExistingAggregateRootValidator constructor. |
29
|
|
|
* |
30
|
|
|
* @param ObjectManager $om |
31
|
|
|
*/ |
32
|
|
|
public function __construct(ObjectManager $om) |
33
|
|
|
{ |
34
|
|
|
$this->om = $om; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
|
|
public function validate($object, Constraint $constraint) |
41
|
|
|
{ |
42
|
|
|
if (!$constraint instanceof ExistingAggregateRoot) { |
43
|
|
|
throw new UnexpectedTypeException($constraint, ExistingAggregateRoot::class); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (null === $object) { |
47
|
|
|
$this->context->addViolation($constraint->nullMessage); |
48
|
|
|
|
49
|
|
|
return; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (null === $constraint->class) { |
53
|
|
|
throw new ConstraintDefinitionException( |
54
|
|
|
'The ExistingAggregateRoot constraint must have a class parameter.' |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
if (!$object instanceof Identity) { |
59
|
|
|
throw new UnexpectedTypeException($object, Identity::class); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** @var ObjectRepository $repo */ |
63
|
|
|
$repo = $this->om->getRepository($constraint->class); |
64
|
|
|
$aggregateRoot = $repo->find($object); |
65
|
|
|
|
66
|
|
|
if (!$aggregateRoot instanceof $constraint->class) { |
67
|
|
|
$this |
68
|
|
|
->context |
69
|
|
|
->buildViolation($constraint->message) |
70
|
|
|
->addViolation(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|