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