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