-
Notifications
You must be signed in to change notification settings - Fork 1
/
RangeRule.php
70 lines (57 loc) · 1.61 KB
/
RangeRule.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
<?php
declare(strict_types = 1);
namespace Elie\Validator\Rule;
/**
* This class verifies that a value exists in an array.
*/
class RangeRule extends AbstractRule
{
/**
* Specific message error code
*/
public const INVALID_RANGE = 'invalidRange';
/**#@+
* Specific options for RangeRule
*/
public const TRIM = 'trim';
public const RANGE = 'range';
/**#@-*/
/**
* Range values.
* Default sets to empty array.
* @var array
*/
protected $range = [];
/**
* Params could have the following structure:
* [
* 'required' => {bool:optional:false by default},
* 'trim' => {bool:optional:true by default:only if value is string},
* 'messages' => {array:optional:key/value message patterns},
* 'range' => {array:optional:empty array by default}
* ]
*/
public function __construct($key, $value, array $params = [])
{
parent::__construct($key, $value, $params);
if (isset($params[$this::RANGE])) {
$this->range = $params[$this::RANGE];
}
$this->messages = $this->messages + [
$this::INVALID_RANGE => '%key%: %value% is out of range %range%',
];
}
public function validate(): int
{
$run = parent::validate();
if ($run !== $this::CHECK) {
return $run;
}
if (! in_array($this->value, $this->range, true)) {
return $this->setAndReturnError($this::INVALID_RANGE, [
'%range%' => $this->stringify($this->range),
]);
}
return $this::VALID;
}
}