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