1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Arrays\ArrayHelper; |
8
|
|
|
use Yiisoft\Validator\Result; |
9
|
|
|
use Yiisoft\Validator\Rule; |
10
|
|
|
use Yiisoft\Validator\ValidationContext; |
11
|
|
|
|
12
|
|
|
class Subset extends Rule |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var iterable |
16
|
|
|
*/ |
17
|
|
|
private iterable $values; |
18
|
|
|
/** |
19
|
|
|
* @var bool whether the comparison is strict (both type and value must be the same) |
20
|
|
|
*/ |
21
|
|
|
private bool $strict = false; |
22
|
|
|
|
23
|
|
|
private string $iterableMessage = 'Value must be iterable'; |
24
|
|
|
|
25
|
|
|
private string $subsetMessage = 'Values must be ones of {values}.'; |
26
|
|
|
|
27
|
4 |
|
public static function rule(iterable $values): self |
28
|
|
|
{ |
29
|
4 |
|
$rule = new self(); |
30
|
4 |
|
$rule->values = $values; |
31
|
4 |
|
return $rule; |
32
|
|
|
} |
33
|
|
|
|
34
|
3 |
|
protected function validateValue($value, ValidationContext $context = null): Result |
35
|
|
|
{ |
36
|
3 |
|
$result = new Result(); |
37
|
|
|
|
38
|
3 |
|
if (!is_iterable($value)) { |
39
|
|
|
$result->addError($this->formatMessage($this->iterableMessage)); |
40
|
|
|
return $result; |
41
|
|
|
} |
42
|
|
|
|
43
|
3 |
|
if (!ArrayHelper::isSubset($value, $this->values, $this->strict)) { |
44
|
1 |
|
$valuesString = '"' . implode('", "', (is_array($this->values) ? $this->values : iterator_to_array($this->values))) . '"'; |
|
|
|
|
45
|
|
|
|
46
|
1 |
|
$result->addError($this->formatMessage($this->subsetMessage, [ |
47
|
1 |
|
'values' => $valuesString, |
48
|
|
|
])); |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
return $result; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function strict(): self |
55
|
|
|
{ |
56
|
|
|
$new = clone $this; |
57
|
|
|
$new->strict = true; |
58
|
|
|
return $new; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function getOptions(): array |
62
|
|
|
{ |
63
|
|
|
return array_merge( |
64
|
|
|
parent::getOptions(), |
65
|
|
|
[ |
66
|
|
|
'iterableMessage' => $this->formatMessage($this->iterableMessage), |
67
|
|
|
'subsetMessage' => $this->formatMessage($this->subsetMessage), |
68
|
|
|
'values' => $this->values, |
69
|
|
|
'strict' => $this->strict, |
70
|
|
|
], |
71
|
|
|
); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|