|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Arrays\ArrayHelper; |
|
8
|
|
|
use Yiisoft\Validator\DataSetInterface; |
|
9
|
|
|
use Yiisoft\Validator\HasValidationErrorMessage; |
|
10
|
|
|
use Yiisoft\Validator\Result; |
|
11
|
|
|
use Yiisoft\Validator\Rule; |
|
12
|
|
|
use Yiisoft\Validator\Rules; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Each validator validates an array by checking each of its elements against a set of rules |
|
16
|
|
|
*/ |
|
17
|
|
|
class Nested extends Rule |
|
18
|
|
|
{ |
|
19
|
|
|
use HasValidationErrorMessage; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @var Rule[][] |
|
23
|
|
|
*/ |
|
24
|
|
|
private iterable $rules; |
|
25
|
|
|
|
|
26
|
|
|
private string $incorrectInputMessage = 'Value should be array or iterable'; |
|
27
|
|
|
private string $message = '{error} {value} given.'; |
|
28
|
|
|
|
|
29
|
4 |
|
public function __construct(iterable $rules) |
|
30
|
|
|
{ |
|
31
|
4 |
|
$this->rules = $rules; |
|
|
|
|
|
|
32
|
4 |
|
} |
|
33
|
|
|
|
|
34
|
4 |
|
protected function validateValue($value, DataSetInterface $dataSet = null): Result |
|
35
|
|
|
{ |
|
36
|
4 |
|
$result = new Result(); |
|
37
|
4 |
|
if (!is_iterable($value)) { |
|
38
|
|
|
$result->addError($this->incorrectInputMessage); |
|
39
|
|
|
return $result; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
4 |
|
foreach ($this->rules as $valuePath => $rules) { |
|
43
|
4 |
|
$validatedValue = ArrayHelper::getValueByPath($value, $valuePath); |
|
44
|
4 |
|
$aggregateRule = new Rules($rules); |
|
45
|
4 |
|
$itemResult = $aggregateRule->validate($validatedValue); |
|
46
|
4 |
|
if ($itemResult->isValid() === false) { |
|
47
|
2 |
|
foreach ($itemResult->getErrors() as $error) { |
|
48
|
2 |
|
$result->addError( |
|
49
|
2 |
|
$this->translateMessage( |
|
50
|
2 |
|
$this->message, |
|
51
|
|
|
[ |
|
52
|
2 |
|
'error' => $error, |
|
53
|
2 |
|
'value' => $validatedValue, |
|
54
|
|
|
] |
|
55
|
|
|
) |
|
56
|
|
|
); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
4 |
|
return $result; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public function incorrectInputMessage(string $message): self |
|
65
|
|
|
{ |
|
66
|
|
|
$new = clone $this; |
|
67
|
|
|
$new->incorrectInputMessage = $message; |
|
68
|
|
|
return $new; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
public function getOptions(): array |
|
72
|
|
|
{ |
|
73
|
|
|
return $this->rules->asArray(); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..