1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
6
|
|
|
|
7
|
|
|
use JetBrains\PhpStorm\Pure; |
8
|
|
|
use Yiisoft\Validator\DataSet\ArrayDataSet; |
9
|
|
|
use Yiisoft\Validator\DataSet\ScalarDataSet; |
10
|
|
|
use function is_array; |
11
|
|
|
use function is_object; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Validator validates {@link DataSetInterface} against rules set for data set attributes. |
15
|
|
|
*/ |
16
|
|
|
final class Validator implements ValidatorInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @param DataSetInterface|mixed|RulesProviderInterface $data |
20
|
|
|
* @param Rule[][] $rules |
21
|
|
|
* @psalm-param iterable<string, Rule[]> $rules |
22
|
|
|
*/ |
23
|
12 |
|
public function validate($data, iterable $rules = []): Result |
24
|
|
|
{ |
25
|
12 |
|
$data = $this->normalizeDataSet($data); |
26
|
12 |
|
if ($data instanceof RulesProviderInterface) { |
27
|
2 |
|
$rules = $data->getRules(); |
28
|
|
|
} |
29
|
|
|
|
30
|
12 |
|
$context = new ValidationContext($data); |
31
|
12 |
|
$result = new Result(); |
32
|
|
|
|
33
|
12 |
|
foreach ($rules as $attribute => $attributeRules) { |
34
|
12 |
|
$ruleSet = new RuleSet($attributeRules); |
35
|
12 |
|
$tempResult = $ruleSet->validate($data->getAttributeValue($attribute), $context->withAttribute($attribute)); |
36
|
|
|
|
37
|
12 |
|
foreach ($tempResult->getErrors() as $error) { |
38
|
3 |
|
$result->addError($error->getMessage(), [$attribute, ...$error->getValuePath()]); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
12 |
|
if ($data instanceof PostValidationHookInterface) { |
43
|
|
|
$data->processValidationResult($result); |
44
|
|
|
} |
45
|
|
|
|
46
|
12 |
|
return $result; |
47
|
|
|
} |
48
|
|
|
|
49
|
12 |
|
#[Pure] |
50
|
|
|
private function normalizeDataSet($data): DataSetInterface |
51
|
|
|
{ |
52
|
12 |
|
if ($data instanceof DataSetInterface) { |
53
|
5 |
|
return $data; |
54
|
|
|
} |
55
|
|
|
|
56
|
7 |
|
if (is_object($data) || is_array($data)) { |
57
|
1 |
|
return new ArrayDataSet((array) $data); |
58
|
|
|
} |
59
|
|
|
|
60
|
6 |
|
return new ScalarDataSet($data); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|