/
InRange.php
98 lines (81 loc) · 2.3 KB
/
InRange.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
declare(strict_types=1);
namespace Yiisoft\Validator\Rule;
use Yiisoft\Arrays\ArrayHelper;
use Yiisoft\Validator\DataSetInterface;
use Yiisoft\Validator\HasValidationErrorMessage;
use Yiisoft\Validator\Result;
use Yiisoft\Validator\Rule;
use function is_iterable;
/**
* In validates that the attribute value is among a list of values.
*
* The range can be specified via the [[range]] property.
* If the [[not]] property is set true, the validator will ensure the attribute value
* is NOT among the specified range.
*
*/
class InRange extends Rule
{
use HasValidationErrorMessage;
/**
* @var iterable
*/
private iterable $range;
/**
* @var bool whether the comparison is strict (both type and value must be the same)
*/
private bool $strict = false;
/**
* @var bool whether to invert the validation logic. Defaults to false. If set to true,
* the attribute value should NOT be among the list of values defined via [[range]].
*/
private bool $not = false;
private string $message = 'This value is invalid.';
public function __construct(iterable $range)
{
$this->range = $range;
}
protected function validateValue($value, DataSetInterface $dataSet = null): Result
{
$in = false;
if (
(is_iterable($value)) &&
ArrayHelper::isSubset($value, $this->range, $this->strict)
) {
$in = true;
}
if (!$in && ArrayHelper::isIn($value, $this->range, $this->strict)) {
$in = true;
}
$result = new Result();
if ($this->not === $in) {
$result->addError($this->translateMessage($this->message));
}
return $result;
}
public function strict(): self
{
$new = clone $this;
$new->strict = true;
return $new;
}
public function not(): self
{
$new = clone $this;
$new->not = true;
return $new;
}
public function getOptions(): array
{
return array_merge(
parent::getOptions(),
[
'message' => $this->translateMessage($this->message),
'range' => $this->range,
'strict' => $this->strict,
'not' => $this->not,
],
);
}
}