1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\DataSet\ArrayDataSet; |
8
|
|
|
use Yiisoft\Validator\DataSet\ScalarDataSet; |
9
|
|
|
use function is_array; |
10
|
|
|
use function is_object; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Validator validates {@link DataSetInterface} against rules set for data set attributes. |
14
|
|
|
*/ |
15
|
|
|
final class Validator implements ValidatorInterface |
16
|
|
|
{ |
17
|
|
|
private ?FormatterInterface $formatter; |
18
|
|
|
|
19
|
12 |
|
public function __construct(?FormatterInterface $formatter = null) |
20
|
|
|
{ |
21
|
12 |
|
$this->formatter = $formatter; |
22
|
12 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param DataSetInterface|mixed|RulesProviderInterface $data |
26
|
|
|
* @param Rule[][] $rules |
27
|
|
|
* @psalm-param iterable<string, Rule[]> $rules |
28
|
|
|
* |
29
|
|
|
* @return ResultSet |
30
|
|
|
*/ |
31
|
12 |
|
public function validate($data, iterable $rules = []): ResultSet |
32
|
|
|
{ |
33
|
12 |
|
$data = $this->normalizeDataSet($data); |
34
|
12 |
|
if ($data instanceof RulesProviderInterface) { |
35
|
|
|
/** @noinspection CallableParameterUseCaseInTypeContextInspection */ |
36
|
2 |
|
$rules = $data->getRules(); |
37
|
|
|
} |
38
|
|
|
|
39
|
12 |
|
$context = new ValidationContext($data); |
40
|
12 |
|
$results = new ResultSet(); |
41
|
|
|
|
42
|
12 |
|
foreach ($rules as $attribute => $attributeRules) { |
43
|
12 |
|
$aggregateRule = new Rules($attributeRules); |
44
|
12 |
|
if ($this->formatter !== null) { |
45
|
|
|
$aggregateRule = $aggregateRule->withFormatter($this->formatter); |
46
|
|
|
} |
47
|
12 |
|
$results->addResult( |
48
|
12 |
|
$attribute, |
49
|
12 |
|
$aggregateRule->validate($data->getAttributeValue($attribute), $context->withAttribute($attribute)) |
50
|
|
|
); |
51
|
|
|
} |
52
|
12 |
|
if ($data instanceof PostValidationHookInterface) { |
53
|
|
|
$data->processValidationResult($results); |
54
|
|
|
} |
55
|
12 |
|
return $results; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function withFormatter(?FormatterInterface $formatter): self |
59
|
|
|
{ |
60
|
|
|
$new = clone $this; |
61
|
|
|
$new->formatter = $formatter; |
62
|
|
|
return $new; |
63
|
|
|
} |
64
|
|
|
|
65
|
12 |
|
private function normalizeDataSet($data): DataSetInterface |
66
|
|
|
{ |
67
|
12 |
|
if ($data instanceof DataSetInterface) { |
68
|
5 |
|
return $data; |
69
|
|
|
} |
70
|
|
|
|
71
|
7 |
|
if (is_object($data) || is_array($data)) { |
72
|
1 |
|
return new ArrayDataSet((array)$data); |
73
|
|
|
} |
74
|
|
|
|
75
|
6 |
|
return new ScalarDataSet($data); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|