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