|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace BrenoRoosevelt\Validation; |
|
5
|
|
|
|
|
6
|
|
|
use BrenoRoosevelt\Validation\Exception\ValidationException; |
|
7
|
|
|
use BrenoRoosevelt\Validation\Exception\ValidationExceptionInterface; |
|
8
|
|
|
|
|
9
|
|
|
class ValidationResultSet |
|
10
|
|
|
{ |
|
11
|
|
|
/** @var ValidationResult[] */ |
|
12
|
|
|
private array $validationResults = []; |
|
13
|
|
|
|
|
14
|
|
|
public function add(ValidationResult ...$errorResult): self |
|
15
|
|
|
{ |
|
16
|
|
|
$instance = clone $this; |
|
17
|
|
|
array_push($instance->validationResults, ...$errorResult); |
|
18
|
|
|
return $instance; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function isOk(): bool |
|
22
|
|
|
{ |
|
23
|
|
|
foreach ($this->validationResults as $violation) { |
|
24
|
|
|
if (!$violation->isOk()) { |
|
25
|
|
|
return false; |
|
26
|
|
|
} |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
return true; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function getErrors(): array |
|
33
|
|
|
{ |
|
34
|
|
|
$errors = []; |
|
35
|
|
|
foreach ($this->validationResults as $violation) { |
|
36
|
|
|
if (null === ($field = $violation->getField())) { |
|
37
|
|
|
array_push($errors, ...$violation->getErrors()); |
|
38
|
|
|
continue; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
if (!isset($errors[$field])) { |
|
42
|
|
|
$errors[$field] = []; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
array_push($errors[$field], ...$violation->getErrors()); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $errors; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function validationResults(): array |
|
52
|
|
|
{ |
|
53
|
|
|
return $this->validationResults; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function isEmpty(): bool |
|
57
|
|
|
{ |
|
58
|
|
|
return empty($this->validationResults); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function guard(?ValidationExceptionInterface $validationException = null): void |
|
62
|
|
|
{ |
|
63
|
|
|
if ($this->isOk()) { |
|
64
|
|
|
return; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
$exception = |
|
68
|
|
|
$validationException instanceof ValidationExceptionInterface ? |
|
69
|
|
|
$validationException : |
|
70
|
|
|
new ValidationException(); |
|
71
|
|
|
|
|
72
|
|
|
foreach ($this->validationResults as $result) { |
|
73
|
|
|
foreach ($result->getErrors() as $error) { |
|
74
|
|
|
$validationException->addError($error, $result->getField()); |
|
|
|
|
|
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
throw $exception; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.