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
|
|
|
/** |
18
|
|
|
* @param DataSetInterface|mixed|RulesProviderInterface $data |
19
|
|
|
* @param Rule[][] $rules |
20
|
|
|
* @psalm-param iterable<string, Rule[]> $rules |
21
|
|
|
*/ |
22
|
12 |
|
public function validate($data, iterable $rules = []): Result |
23
|
|
|
{ |
24
|
12 |
|
$data = $this->normalizeDataSet($data); |
25
|
12 |
|
if ($data instanceof RulesProviderInterface) { |
26
|
2 |
|
$rules = $data->getRules(); |
27
|
|
|
} |
28
|
|
|
|
29
|
12 |
|
$context = new ValidationContext($data); |
30
|
12 |
|
$result = new Result(); |
31
|
|
|
|
32
|
12 |
|
foreach ($rules as $attribute => $attributeRules) { |
33
|
12 |
|
$ruleSet = new RuleSet($attributeRules); |
34
|
12 |
|
$tempResult = $ruleSet->validate($data->getAttributeValue($attribute), $context->withAttribute($attribute)); |
35
|
|
|
|
36
|
12 |
|
foreach ($tempResult->getErrors() as $error) { |
37
|
3 |
|
$result->addError($error->getMessage(), [$attribute, ...$error->getValuePath()]); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
12 |
|
if ($data instanceof PostValidationHookInterface) { |
42
|
|
|
$data->processValidationResult($result); |
43
|
|
|
} |
44
|
|
|
|
45
|
12 |
|
return $result; |
46
|
|
|
} |
47
|
|
|
|
48
|
12 |
|
private function normalizeDataSet($data): DataSetInterface |
49
|
|
|
{ |
50
|
12 |
|
if ($data instanceof DataSetInterface) { |
51
|
5 |
|
return $data; |
52
|
|
|
} |
53
|
|
|
|
54
|
7 |
|
if (is_object($data) || is_array($data)) { |
55
|
1 |
|
return new ArrayDataSet((array) $data); |
56
|
|
|
} |
57
|
|
|
|
58
|
6 |
|
return new ScalarDataSet($data); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|