1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace App\Exception; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Import classes |
7
|
|
|
*/ |
8
|
|
|
use Symfony\Component\Validator\ConstraintViolationListInterface; |
9
|
|
|
use Symfony\Component\Validator\Validator\ValidatorInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Import functions |
13
|
|
|
*/ |
14
|
|
|
use function get_class; |
15
|
|
|
use function sprintf; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* InvalidEntityException |
19
|
|
|
*/ |
20
|
|
|
final class InvalidEntityException extends AbstractException |
21
|
|
|
{ |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* An invalid entity |
25
|
|
|
* |
26
|
|
|
* @var object |
27
|
|
|
*/ |
28
|
|
|
private $invalidEntity; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* An entity violations |
32
|
|
|
* |
33
|
|
|
* @var ConstraintViolationListInterface |
34
|
|
|
*/ |
35
|
|
|
private $entityViolations; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Constructor of the class |
39
|
|
|
* |
40
|
|
|
* @param object $invalidEntity |
41
|
|
|
* @param ConstraintViolationListInterface $entityViolations |
42
|
|
|
*/ |
43
|
|
|
public function __construct(object $invalidEntity, ConstraintViolationListInterface $entityViolations) |
44
|
|
|
{ |
45
|
|
|
$this->invalidEntity = $invalidEntity; |
46
|
|
|
$this->entityViolations = $entityViolations; |
47
|
|
|
|
48
|
|
|
parent::__construct(sprintf('Invalid the entity "%s"', get_class($invalidEntity))); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Gets an invalid entity |
53
|
|
|
* |
54
|
|
|
* @return object |
55
|
|
|
*/ |
56
|
|
|
public function getInvalidEntity() : object |
57
|
|
|
{ |
58
|
|
|
return $this->invalidEntity; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Gets an entity violations |
63
|
|
|
* |
64
|
|
|
* @return ConstraintViolationListInterface |
65
|
|
|
*/ |
66
|
|
|
public function getEntityViolations() : ConstraintViolationListInterface |
67
|
|
|
{ |
68
|
|
|
return $this->entityViolations; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Throws the exception if the given entity isn't valid |
73
|
|
|
* |
74
|
|
|
* @param object $entity |
75
|
|
|
* @param ValidatorInterface $validator |
76
|
|
|
* |
77
|
|
|
* @return void |
78
|
|
|
*/ |
79
|
|
|
public static function assert(object $entity, ValidatorInterface $validator) : void |
80
|
|
|
{ |
81
|
|
|
$violations = $validator->validate($entity); |
82
|
|
|
|
83
|
|
|
if (0 === $violations->count()) { |
84
|
|
|
return; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
throw new self($entity, $violations); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|