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
|
4 |
|
public function __construct(?FormatterInterface $formatter = null) |
23
|
|
|
{ |
24
|
4 |
|
$this->formatter = $formatter ?? new Formatter(); |
25
|
|
|
} |
26
|
|
|
|
27
|
4 |
|
public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result |
28
|
|
|
{ |
29
|
4 |
|
if (!$rule instanceof Each) { |
30
|
1 |
|
throw new UnexpectedRuleException(Each::class, $rule); |
31
|
|
|
} |
32
|
|
|
|
33
|
3 |
|
$rules = $rule->getRules(); |
34
|
3 |
|
if ($rules === []) { |
35
|
|
|
throw new InvalidArgumentException('Rules are required.'); |
36
|
|
|
} |
37
|
|
|
|
38
|
3 |
|
$result = new Result(); |
39
|
3 |
|
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
|
3 |
|
foreach ($value as $index => $item) { |
50
|
|
|
/** @var array<mixed, RuleInterface[]> $rule */ |
51
|
3 |
|
$rule = [$index => $rules]; |
52
|
3 |
|
$itemResult = $context?->getValidator()->validate($item, $rule); |
53
|
3 |
|
if ($itemResult->isValid()) { |
54
|
3 |
|
continue; |
55
|
|
|
} |
56
|
|
|
|
57
|
2 |
|
foreach ($itemResult->getErrors() as $error) { |
58
|
2 |
|
$result->addError($error->getMessage(), $error->getValuePath()); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
3 |
|
return $result; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|