-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathRange.php
executable file
·149 lines (134 loc) · 3 KB
/
Range.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<?php
namespace Utopia\Http\Validator;
/**
* Range
*
* Validates that an number is in range.
*/
class Range extends Numeric
{
/**
* @var int|float
*/
protected int|float $min;
/**
* @var int|float
*/
protected int|float $max;
/**
* @var string
*/
protected string $format;
/**
* @param int|float $min
* @param int|float $max
* @param string $format
*/
public function __construct(int|float $min, int|float $max, string $format = self::TYPE_INTEGER)
{
$this->min = $min;
$this->max = $max;
$this->format = $format;
}
/**
* Get Range Minimum Value
*
* @return int|float
*/
public function getMin(): int|float
{
return $this->min;
}
/**
* Get Range Maximum Value
*
* @return int|float
*/
public function getMax(): int|float
{
return $this->max;
}
/**
* Get Range Format
*
* @return string
*/
public function getFormat(): string
{
return $this->format;
}
/**
* Get Description
*
* Returns validator description
*
* @return string
*/
public function getDescription(): string
{
return 'Value must be a valid range between '.\number_format($this->min).' and '.\number_format($this->max);
}
/**
* Is array
*
* Function will return true if object is array.
*
* @return bool
*/
public function isArray(): bool
{
return false;
}
/**
* Get Type
*
* Returns validator type.
*
* @return string
*/
public function getType(): string
{
return $this->format;
}
/**
* Is valid
*
* Validation will pass when $value number is bigger or equal than $min number and lower or equal than $max.
* Not strict, considers any valid integer to be a valid float
* Considers infinity to be a valid integer
*
* @param mixed $value
* @return bool
*/
public function isValid(mixed $value): bool
{
if (!parent::isValid($value)) {
return false;
}
switch ($this->format) {
case self::TYPE_INTEGER:
// Accept infinity as an integer
// Since gettype(INF) === TYPE_FLOAT
if ($value === INF || $value === -INF) {
break; // move to check if value is within range
}
$value = $value + 0;
if (!is_int($value)) {
return false;
}
break;
case self::TYPE_FLOAT:
if (!is_numeric($value)) {
return false;
}
$value = $value + 0.0;
break;
default:
return false;
}
if ($this->min <= $value && $this->max >= $value) {
return true;
}
return false;
}
}