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
|
11 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
21
|
|
|
{ |
22
|
11 |
|
if (!$rule instanceof Each) { |
23
|
1 |
|
throw new UnexpectedRuleException(Each::class, $rule); |
24
|
|
|
} |
25
|
|
|
|
26
|
10 |
|
$rules = $rule->getRules(); |
27
|
10 |
|
if ($rules === []) { |
28
|
|
|
throw new InvalidArgumentException('Rules are required.'); |
29
|
|
|
} |
30
|
|
|
|
31
|
10 |
|
$result = new Result(); |
32
|
10 |
|
if (!is_iterable($value)) { |
33
|
1 |
|
$result->addError( |
34
|
1 |
|
message: $rule->getIncorrectInputMessage(), |
35
|
1 |
|
parameters: ['value' => $value] |
36
|
|
|
); |
37
|
|
|
|
38
|
1 |
|
return $result; |
39
|
|
|
} |
40
|
|
|
|
41
|
9 |
|
foreach ($value as $index => $item) { |
42
|
|
|
/** @var array<mixed, Closure|Closure[]|RuleInterface|RuleInterface[]> $rule */ |
43
|
9 |
|
$rule = [$index => $rules]; |
44
|
9 |
|
$itemResult = $context->getValidator()->validate($item, $rule, $context); |
45
|
9 |
|
if ($itemResult->isValid()) { |
46
|
8 |
|
continue; |
47
|
|
|
} |
48
|
|
|
|
49
|
8 |
|
foreach ($itemResult->getErrors() as $error) { |
50
|
8 |
|
if ($error->getValuePath() === []) { |
51
|
7 |
|
$errorKey = [$index]; |
52
|
|
|
} else { |
53
|
5 |
|
$errorKey = [$index, ...$error->getValuePath()]; |
54
|
|
|
} |
55
|
|
|
|
56
|
8 |
|
$result->addError( |
57
|
8 |
|
message: $error->getMessage(), |
58
|
|
|
valuePath: $errorKey, |
59
|
8 |
|
parameters: $error->getParameters() |
60
|
|
|
); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
9 |
|
return $result; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|