1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace jin2chen\YiiValidator\Rule; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use jin2chen\YiiValidator\NestRule; |
9
|
|
|
use Yiisoft\Validator\DataSetInterface; |
10
|
|
|
use Yiisoft\Validator\Result; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
use function is_array; |
14
|
|
|
use function is_scalar; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @method Many withRules(iterable $rules) |
18
|
|
|
*/ |
19
|
|
|
final class Many extends NestRule |
20
|
|
|
{ |
21
|
|
|
private ?string $indexKey = null; |
22
|
|
|
|
23
|
2 |
|
public static function rule(): Many |
24
|
|
|
{ |
25
|
2 |
|
return new Many(); |
26
|
|
|
} |
27
|
|
|
|
28
|
1 |
|
public function withIndexKey(string $key): self |
29
|
|
|
{ |
30
|
1 |
|
$new = clone $this; |
31
|
1 |
|
$new->indexKey = $key; |
32
|
1 |
|
return $new; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param mixed $data |
37
|
|
|
* @param string $default |
38
|
|
|
* @return string |
39
|
|
|
*/ |
40
|
2 |
|
private function getIndexKey($data, string $default): string |
41
|
|
|
{ |
42
|
2 |
|
if ($this->indexKey === null) { |
43
|
1 |
|
return $default; |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
if (is_array($data)) { |
47
|
|
|
/** @var scalar|object|array $result */ |
48
|
1 |
|
$result = $data[$this->indexKey] ?? $default; |
49
|
1 |
|
return is_scalar($result) ? (string)$result : $default; |
|
|
|
|
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if ($data instanceof DataSetInterface) { |
53
|
|
|
/** @var scalar|object|array $result */ |
54
|
|
|
$result = $data->getAttributeValue($this->indexKey); |
55
|
|
|
return is_scalar($result) ? (string)$result : $default; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $default; |
59
|
|
|
} |
60
|
|
|
|
61
|
2 |
|
protected function validateValue($value, ValidationContext $context = null): Result |
62
|
|
|
{ |
63
|
2 |
|
if (!is_array($value)) { |
64
|
|
|
throw new InvalidArgumentException('Value must be an array.'); |
65
|
|
|
} |
66
|
|
|
|
67
|
2 |
|
if (!$context) { |
68
|
|
|
throw new InvalidArgumentException('Context must be set.'); |
69
|
|
|
} |
70
|
|
|
|
71
|
2 |
|
$attribute = $context->getAttribute() ?: ''; |
72
|
|
|
/** @var DataSetInterface|array $item */ |
73
|
2 |
|
foreach ($value as $index => $item) { |
74
|
2 |
|
$results = $this->getValidator()->validate($item, $this->getRules()); |
75
|
2 |
|
$this->addResultSet($results, $attribute . '.' . $this->getIndexKey($item, (string)$index)); |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
return new Result(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|