|
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
|
|
|
public function setValidator(ValidatorInterface $validator): EntityValidatorInterface |
|
24
|
|
|
{ |
|
25
|
|
|
$this->validator = $validator; |
|
26
|
|
|
|
|
27
|
|
|
return $this; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function setEntity(EntityInterface $entity): EntityValidatorInterface |
|
31
|
|
|
{ |
|
32
|
|
|
$this->entity = $entity; |
|
33
|
|
|
|
|
34
|
|
|
return $this; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function isValid(): bool |
|
38
|
|
|
{ |
|
39
|
|
|
return $this->validator->validate($this->entity)->count() === 0; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @param ConstraintViolationListInterface $errors |
|
44
|
|
|
* |
|
45
|
|
|
* @throws ValidationException |
|
46
|
|
|
*/ |
|
47
|
|
|
protected function throwExceptionIfErrors(ConstraintViolationListInterface $errors) |
|
48
|
|
|
{ |
|
49
|
|
|
if ($errors->count() === 0) { |
|
50
|
|
|
return; |
|
51
|
|
|
} |
|
52
|
|
|
throw new ValidationException($errors, $this->entity); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Validate the whole entity |
|
57
|
|
|
* |
|
58
|
|
|
* @throws ValidationException |
|
59
|
|
|
*/ |
|
60
|
|
|
public function validate(): void |
|
61
|
|
|
{ |
|
62
|
|
|
$errors = $this->validator->validate($this->entity); |
|
63
|
|
|
$this->throwExceptionIfErrors($errors); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Validate a single entity property |
|
68
|
|
|
* |
|
69
|
|
|
* @param string $propertyName |
|
70
|
|
|
* |
|
71
|
|
|
* @throws ValidationException |
|
72
|
|
|
*/ |
|
73
|
|
|
public function validateProperty(string $propertyName): void |
|
74
|
|
|
{ |
|
75
|
|
|
$errors = $this->validator->validateProperty($this->entity, $propertyName); |
|
76
|
|
|
$this->throwExceptionIfErrors($errors); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|