|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
|
8
|
|
|
use Yiisoft\Translator\TranslatorInterface; |
|
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 __construct(private TranslatorInterface $translator) |
|
21
|
|
|
{ |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
10 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
|
25
|
|
|
{ |
|
26
|
10 |
|
if (!$rule instanceof Each) { |
|
27
|
1 |
|
throw new UnexpectedRuleException(Each::class, $rule); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** @var Each $eachRule */ |
|
31
|
9 |
|
$eachRule = $rule; |
|
32
|
|
|
|
|
33
|
9 |
|
$rules = $rule->getRules(); |
|
34
|
9 |
|
if ($rules === []) { |
|
35
|
|
|
throw new InvalidArgumentException('Rules are required.'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
9 |
|
$result = new Result(); |
|
39
|
9 |
|
if (!is_iterable($value)) { |
|
40
|
|
|
$formattedMessage = $this->translator->translate( |
|
41
|
|
|
$rule->getIncorrectInputMessage(), |
|
42
|
|
|
['attribute' => $context->getAttribute(), 'value' => $value] |
|
43
|
|
|
); |
|
44
|
|
|
$result->addError($formattedMessage); |
|
45
|
|
|
|
|
46
|
|
|
return $result; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
9 |
|
foreach ($value as $index => $item) { |
|
50
|
|
|
/** @var array<mixed, \Closure|\Closure[]|RuleInterface|RuleInterface[]> $rule */ |
|
51
|
9 |
|
$rule = [$index => $rules]; |
|
52
|
9 |
|
$itemResult = $context->getValidator()->validate($item, $rule); |
|
53
|
9 |
|
if ($itemResult->isValid()) { |
|
54
|
8 |
|
continue; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
8 |
|
foreach ($itemResult->getErrors() as $error) { |
|
58
|
8 |
|
if ($error->getValuePath() === []) { |
|
59
|
7 |
|
$errorKey = [$index]; |
|
60
|
7 |
|
$formatMessage = true; |
|
61
|
|
|
} else { |
|
62
|
5 |
|
$errorKey = [$index, ...$error->getValuePath()]; |
|
63
|
5 |
|
$formatMessage = false; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
8 |
|
$message = !$formatMessage ? $error->getMessage() : $this->translator->translate($eachRule->getMessage(), [ |
|
67
|
7 |
|
'error' => $error->getMessage(), |
|
68
|
|
|
'value' => $item, |
|
69
|
|
|
]); |
|
70
|
8 |
|
$result->addError($message, $errorKey); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
9 |
|
return $result; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|