|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Closure; |
|
8
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
|
9
|
|
|
use Yiisoft\Validator\Result; |
|
10
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
|
11
|
|
|
use Yiisoft\Validator\RuleInterface; |
|
12
|
|
|
use Yiisoft\Validator\ValidationContext; |
|
13
|
|
|
|
|
14
|
|
|
use function is_int; |
|
15
|
|
|
use function is_string; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Validates an array by checking each of its elements against a set of rules. |
|
19
|
|
|
*/ |
|
20
|
|
|
final class EachHandler implements RuleHandlerInterface |
|
21
|
|
|
{ |
|
22
|
12 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
|
23
|
|
|
{ |
|
24
|
12 |
|
if (!$rule instanceof Each) { |
|
25
|
1 |
|
throw new UnexpectedRuleException(Each::class, $rule); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
11 |
|
$rules = $rule->getRules(); |
|
29
|
|
|
|
|
30
|
11 |
|
$result = new Result(); |
|
31
|
11 |
|
if (!is_iterable($value)) { |
|
32
|
2 |
|
$result->addError($rule->getIncorrectInputMessage(), [ |
|
33
|
2 |
|
'attribute' => $context->getAttribute(), |
|
34
|
2 |
|
'type' => get_debug_type($value), |
|
35
|
|
|
]); |
|
36
|
|
|
|
|
37
|
2 |
|
return $result; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** @var mixed $item */ |
|
41
|
9 |
|
foreach ($value as $index => $item) { |
|
42
|
9 |
|
if (!is_int($index) && !is_string($index)) { |
|
43
|
1 |
|
$result->addError($rule->getIncorrectInputKeyMessage(), [ |
|
44
|
1 |
|
'attribute' => $context->getAttribute(), |
|
45
|
1 |
|
'type' => get_debug_type($value), |
|
46
|
|
|
]); |
|
47
|
|
|
|
|
48
|
1 |
|
return $result; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** @var array<mixed, Closure|Closure[]|RuleInterface|RuleInterface[]> $relatedRule */ |
|
52
|
8 |
|
$relatedRule = [$index => $rules]; |
|
53
|
|
|
|
|
54
|
8 |
|
$itemResult = $context->getValidator()->validate($item, $relatedRule); |
|
55
|
8 |
|
if ($itemResult->isValid()) { |
|
56
|
7 |
|
continue; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
7 |
|
foreach ($itemResult->getErrors() as $error) { |
|
60
|
7 |
|
$result->addError( |
|
61
|
7 |
|
$error->getMessage(), |
|
62
|
7 |
|
$error->getParameters(), |
|
63
|
7 |
|
$error->getValuePath() === [] ? [$index] : [$index, ...$error->getValuePath()], |
|
64
|
|
|
); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
8 |
|
return $result; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|