1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Linna Filter |
5
|
|
|
* |
6
|
|
|
* @author Sebastian Rapetti <[email protected]> |
7
|
|
|
* @copyright (c) 2018, Sebastian Rapetti |
8
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types = 1); |
11
|
|
|
|
12
|
|
|
namespace Linna\Filter\Rules; |
13
|
|
|
|
14
|
|
|
use UnexpectedValueException; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Check if a number is included or not on interval using ><, <>, >=<, <=> operators. |
18
|
|
|
*/ |
19
|
|
|
class NumberInterval extends AbstractNumber |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var array Arguments expected. |
23
|
|
|
*/ |
24
|
|
|
private $arguments = ['string', 'number', 'number']; |
|
|
|
|
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Validate. |
28
|
|
|
* |
29
|
|
|
* @param int|float|string $received |
30
|
|
|
* @param string $operator |
31
|
|
|
* @param int|float|string $min |
32
|
|
|
* @param int|float|string $max |
33
|
|
|
* |
34
|
|
|
* @return bool |
35
|
|
|
*/ |
36
|
22 |
|
public function validate($received, string $operator, $min, $max): bool |
37
|
|
|
{ |
38
|
22 |
|
if (!is_numeric($received)) { |
39
|
1 |
|
return true; |
40
|
|
|
} |
41
|
|
|
|
42
|
21 |
|
if ($this->switchOperator($operator, $received, $min, $max)) { |
43
|
10 |
|
return false; |
44
|
|
|
} |
45
|
|
|
|
46
|
10 |
|
return true; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Perform correct operation from passed operator. |
51
|
|
|
* |
52
|
|
|
* @param string $operator |
53
|
|
|
* @param int|float|string $numberReceived |
54
|
|
|
* @param int|float|string $min |
55
|
|
|
* @param int|float|string $max |
56
|
|
|
* |
57
|
|
|
* @return bool |
58
|
|
|
* |
59
|
|
|
* @throws UnexpectedValueException if unknown operator is provided. |
60
|
|
|
*/ |
61
|
21 |
|
private function switchOperator(string $operator, &$numberReceived, &$min, &$max): bool |
62
|
|
|
{ |
63
|
|
|
switch ($operator) { |
64
|
21 |
|
case '><': //inside interval exclusive |
65
|
5 |
|
return $numberReceived > $min && $numberReceived < $max; |
66
|
16 |
|
case '>=<': //inside interval inclusive |
67
|
5 |
|
return $numberReceived >= $min && $numberReceived <= $max; |
68
|
11 |
|
case '<>': //outside interval exclusive |
69
|
5 |
|
return $numberReceived < $min || $numberReceived > $max; |
70
|
6 |
|
case '<=>': //outside interval inclusive |
71
|
5 |
|
return $numberReceived <= $min || $numberReceived >= $max;; |
72
|
|
|
default: |
73
|
1 |
|
throw new UnexpectedValueException("Unknown comparson operator ({$operator}). Permitted ><, <>, >=<, <=>"); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|