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