|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
|
6
|
|
|
|
|
7
|
|
|
use ArrayIterator; |
|
8
|
|
|
use InvalidArgumentException; |
|
9
|
|
|
use IteratorAggregate; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* ResultSet stores validation result of each attribute from {@link DataSetInterface}. |
|
13
|
|
|
* It is typically obtained by validating data set with {@link Validator}. |
|
14
|
|
|
*/ |
|
15
|
|
|
final class ResultSet implements IteratorAggregate |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @var Result[] |
|
19
|
|
|
*/ |
|
20
|
|
|
private array $results = []; |
|
21
|
|
|
private bool $hasErrors = false; |
|
22
|
|
|
|
|
23
|
9 |
|
public function addResult(string $attribute, Result $result): void |
|
24
|
|
|
{ |
|
25
|
9 |
|
if (!$result->isValid()) { |
|
26
|
8 |
|
$this->hasErrors = true; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
9 |
|
if (!isset($this->results[$attribute])) { |
|
30
|
9 |
|
$this->results[$attribute] = $result; |
|
31
|
9 |
|
return; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
2 |
|
if ($result->isValid()) { |
|
35
|
1 |
|
return; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
1 |
|
foreach ($result->getErrors() as $error) { |
|
39
|
1 |
|
$this->results[$attribute]->addError($error); |
|
40
|
|
|
} |
|
41
|
1 |
|
} |
|
42
|
|
|
|
|
43
|
6 |
|
public function getResult(string $attribute): Result |
|
44
|
|
|
{ |
|
45
|
6 |
|
if (!isset($this->results[$attribute])) { |
|
46
|
|
|
throw new InvalidArgumentException("There is no result for attribute \"$attribute\""); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
6 |
|
return $this->results[$attribute]; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
public function getIterator(): ArrayIterator |
|
53
|
|
|
{ |
|
54
|
1 |
|
return new ArrayIterator($this->results); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
1 |
|
public function getErrors(): self |
|
58
|
|
|
{ |
|
59
|
1 |
|
$resultSet = new self(); |
|
60
|
1 |
|
foreach ($this->results as $attribute => $result) { |
|
61
|
1 |
|
if (!$result->isValid()) { |
|
62
|
1 |
|
$resultSet->addResult($attribute, $result); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
return $resultSet; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
2 |
|
public function hasErrors(): bool |
|
70
|
|
|
{ |
|
71
|
2 |
|
return $this->hasErrors === false; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|