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
|
|
|
public function __construct(iterable $values) |
28
|
|
|
{ |
29
|
|
|
$this->values = $values; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function validateValue($value, ValidationContext $context = null): Result |
33
|
|
|
{ |
34
|
|
|
$result = new Result(); |
35
|
|
|
|
36
|
|
|
if (!is_iterable($value)) { |
37
|
|
|
$result->addError($this->formatMessage($this->iterableMessage)); |
38
|
|
|
return $result; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (!ArrayHelper::isSubset($value, $this->values, $this->strict)) { |
42
|
|
|
|
43
|
|
|
$valuesString = '"' . implode('", "', (is_array($this->values) ? $values : iterator_to_array($this->values))) . '"'; |
|
|
|
|
44
|
|
|
|
45
|
|
|
$result->addError($this->formatMessage($this->subsetMessage, [ |
46
|
|
|
'values' => $valuesString, |
47
|
|
|
])); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $result; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function strict(): self |
54
|
|
|
{ |
55
|
|
|
$new = clone $this; |
56
|
|
|
$new->strict = true; |
57
|
|
|
return $new; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function getOptions(): array |
61
|
|
|
{ |
62
|
|
|
return array_merge( |
63
|
|
|
parent::getOptions(), |
64
|
|
|
[ |
65
|
|
|
'iterableMessage' => $this->formatMessage($this->iterableMessage), |
66
|
|
|
'subsetMessage' => $this->formatMessage($this->subsetMessage), |
67
|
|
|
'values' => $this->values, |
68
|
|
|
'strict' => $this->strict, |
69
|
|
|
], |
70
|
|
|
); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|