|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Validator\HasValidationErrorMessage; |
|
8
|
|
|
use Yiisoft\Validator\Result; |
|
9
|
|
|
use Yiisoft\Validator\Rule; |
|
10
|
|
|
use Yiisoft\Validator\RuleSet; |
|
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Each validator validates an array by checking each of its elements against a set of rules |
|
15
|
|
|
*/ |
|
16
|
|
|
final class Each extends Rule |
|
17
|
|
|
{ |
|
18
|
|
|
use HasValidationErrorMessage; |
|
19
|
|
|
|
|
20
|
|
|
private RuleSet $ruleSet; |
|
21
|
|
|
|
|
22
|
|
|
private string $incorrectInputMessage = 'Value should be array or iterable.'; |
|
23
|
|
|
private string $message = '{error} {value} given.'; |
|
24
|
|
|
|
|
25
|
6 |
|
public static function rule(RuleSet $ruleSet): self |
|
26
|
|
|
{ |
|
27
|
6 |
|
$rule = new self(); |
|
28
|
6 |
|
$rule->ruleSet = $ruleSet; |
|
29
|
6 |
|
return $rule; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
3 |
|
protected function validateValue($value, ValidationContext $context = null): Result |
|
33
|
|
|
{ |
|
34
|
3 |
|
$result = new Result(); |
|
35
|
3 |
|
if (!is_iterable($value)) { |
|
36
|
|
|
$result->addError($this->incorrectInputMessage); |
|
37
|
|
|
return $result; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
3 |
|
foreach ($value as $index => $item) { |
|
41
|
3 |
|
$itemResult = $this->ruleSet->validate($item, $context); |
|
42
|
3 |
|
if ($itemResult->isValid()) { |
|
43
|
2 |
|
continue; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
3 |
|
foreach ($itemResult->getErrorObjects() as $error) { |
|
47
|
3 |
|
if (!is_array($item)) { |
|
48
|
3 |
|
$errorKey = [$index]; |
|
49
|
3 |
|
$formatMessage = true; |
|
50
|
|
|
} else { |
|
51
|
1 |
|
$errorKey = [$index, ...$error->getValuePath()]; |
|
52
|
1 |
|
$formatMessage = false; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
3 |
|
$message = !$formatMessage ? $error->getMessage() : $this->formatMessage($this->message, [ |
|
56
|
3 |
|
'error' => $error->getMessage(), |
|
57
|
3 |
|
'value' => $item, |
|
58
|
|
|
]); |
|
59
|
|
|
|
|
60
|
3 |
|
$result->addError($message, $errorKey); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
3 |
|
return $result; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public function incorrectInputMessage(string $message): self |
|
68
|
|
|
{ |
|
69
|
|
|
$new = clone $this; |
|
70
|
|
|
$new->incorrectInputMessage = $message; |
|
71
|
|
|
return $new; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
2 |
|
public function getOptions(): array |
|
75
|
|
|
{ |
|
76
|
2 |
|
return $this->ruleSet->asArray(); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|