Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
34 / 34 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
Between | |
100.00% |
34 / 34 |
|
100.00% |
3 / 3 |
9 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
validate | |
100.00% |
26 / 26 |
|
100.00% |
1 / 1 |
7 | |||
getInverseError | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace Verja\Validator; |
4 | |
5 | use Verja\Error; |
6 | use Verja\Validator; |
7 | |
8 | class Between extends Validator |
9 | { |
10 | /** @var float|int */ |
11 | protected $min; |
12 | |
13 | /** @var float|int */ |
14 | protected $max; |
15 | |
16 | /** |
17 | * Between constructor. |
18 | * |
19 | * @param float|int $min |
20 | * @param float|int $max |
21 | */ |
22 | public function __construct($min = null, $max = null) |
23 | { |
24 | $this->min = $min; |
25 | $this->max = $max; |
26 | } |
27 | |
28 | /** |
29 | * Validate $value |
30 | * |
31 | * @param mixed $value |
32 | * @param array $context |
33 | * @return bool |
34 | */ |
35 | public function validate($value, array $context = []): bool |
36 | { |
37 | if (!is_int($value) && !is_double($value)) { |
38 | $this->error = new Error('NO_NUMBER', $value, 'value should be a number'); |
39 | return false; |
40 | } |
41 | |
42 | if (!is_null($this->min) && $this->min > $value) { |
43 | $this->error = new Error( |
44 | 'TOO_SMALL', |
45 | $value, |
46 | sprintf('value should be at least %s', $this->min), |
47 | [ |
48 | 'min' => $this->min, |
49 | 'max' => $this->max, |
50 | ] |
51 | ); |
52 | return false; |
53 | } |
54 | |
55 | if (!is_null($this->max) && $this->max < $value) { |
56 | $this->error = new Error( |
57 | 'TOO_BIG', |
58 | $value, |
59 | sprintf('value should be maximal %s', $this->max), |
60 | [ |
61 | 'min' => $this->min, |
62 | 'max' => $this->max, |
63 | ] |
64 | ); |
65 | return false; |
66 | } |
67 | |
68 | return true; |
69 | } |
70 | |
71 | public function getInverseError($value) |
72 | { |
73 | return new Error( |
74 | 'BETWEEN', |
75 | $value, |
76 | sprintf('value should not be between %d and %d', $this->min, $this->max), |
77 | ['min' => $this->min, 'max' => $this->max] |
78 | ); |
79 | } |
80 | } |