1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Validation; |
4
|
|
|
|
5
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\EntityInterface; |
6
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Interfaces\Validation\EntityValidatorInterface; |
7
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Exception\ValidationException; |
8
|
|
|
use Symfony\Component\Validator\ConstraintViolationListInterface; |
9
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
10
|
|
|
|
11
|
|
|
class EntityValidator implements EntityValidatorInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var ValidatorInterface |
15
|
|
|
*/ |
16
|
|
|
protected $validator; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var EntityInterface |
20
|
|
|
*/ |
21
|
|
|
protected $entity; |
22
|
|
|
|
23
|
3 |
|
public function setValidator(ValidatorInterface $validator): EntityValidatorInterface |
24
|
|
|
{ |
25
|
3 |
|
$this->validator = $validator; |
26
|
|
|
|
27
|
3 |
|
return $this; |
28
|
|
|
} |
29
|
|
|
|
30
|
3 |
|
public function setEntity(EntityInterface $entity): EntityValidatorInterface |
31
|
|
|
{ |
32
|
3 |
|
$this->entity = $entity; |
33
|
|
|
|
34
|
3 |
|
return $this; |
35
|
|
|
} |
36
|
|
|
|
37
|
3 |
|
public function isValid(): bool |
38
|
|
|
{ |
39
|
3 |
|
return $this->validator->validate($this->entity)->count() === 0; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Validate the whole entity |
44
|
|
|
* |
45
|
|
|
* @throws ValidationException |
46
|
|
|
*/ |
47
|
|
|
public function validate(): void |
48
|
|
|
{ |
49
|
|
|
$errors = $this->validator->validate($this->entity); |
50
|
|
|
$this->throwExceptionIfErrors($errors); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param ConstraintViolationListInterface $errors |
55
|
|
|
* |
56
|
|
|
* @throws ValidationException |
57
|
|
|
*/ |
58
|
2 |
|
protected function throwExceptionIfErrors(ConstraintViolationListInterface $errors): void |
59
|
|
|
{ |
60
|
2 |
|
if ($errors->count() === 0) { |
61
|
1 |
|
return; |
62
|
|
|
} |
63
|
1 |
|
throw new ValidationException($errors, $this->entity); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Validate a single entity property |
68
|
|
|
* |
69
|
|
|
* @param string $propertyName |
70
|
|
|
* |
71
|
|
|
* @throws ValidationException |
72
|
|
|
*/ |
73
|
2 |
|
public function validateProperty(string $propertyName): void |
74
|
|
|
{ |
75
|
2 |
|
$errors = $this->validator->validateProperty($this->entity, $propertyName); |
76
|
2 |
|
$this->throwExceptionIfErrors($errors); |
77
|
1 |
|
} |
78
|
|
|
} |
79
|
|
|
|