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