1
|
|
|
<?php |
2
|
|
|
namespace Comfort\Validator; |
3
|
|
|
|
4
|
|
|
use Comfort\Comfort; |
5
|
|
|
|
6
|
|
|
class NumberValidator extends AbstractValidator |
7
|
|
|
{ |
8
|
|
|
public function __construct(Comfort $comfort) |
9
|
|
|
{ |
10
|
|
|
parent::__construct($comfort); |
11
|
|
|
|
12
|
|
|
$this->toBool(false); |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Validate number is no less than $min |
17
|
|
|
* |
18
|
|
|
* @param $min |
19
|
|
|
* @return $this |
20
|
|
|
*/ |
21
|
|
|
public function min($min) |
22
|
|
|
{ |
23
|
|
|
return $this->add(function($value, $nameKey) use ($min) { |
24
|
|
|
if ($value < $min) { |
25
|
|
|
return $this->createError('number.min', $value, $nameKey); |
26
|
|
|
} |
27
|
|
|
}); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Validate number is no more than $max |
32
|
|
|
* |
33
|
|
|
* @param $max |
34
|
|
|
* @return $this |
35
|
|
|
*/ |
36
|
|
|
public function max($max) |
37
|
|
|
{ |
38
|
|
|
return $this->add(function($value, $nameKey) use ($max) { |
39
|
|
|
if ($value > $max) { |
40
|
|
|
return $this->createError('number.max', $value, $nameKey); |
41
|
|
|
} |
42
|
|
|
}); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Validate precision of number is $precision |
47
|
|
|
* |
48
|
|
|
* @todo think if less kludgy way to do this... |
49
|
|
|
* @param $precision |
50
|
|
|
* @return $this |
51
|
|
|
*/ |
52
|
|
|
public function precision($precision) |
53
|
|
|
{ |
54
|
|
|
return $this->add(function($value, $nameKey) use ($precision) { |
55
|
|
|
if (strlen(substr($value, strpos($value, '.') + 1)) != $precision) { |
56
|
|
|
return $this->createError('number.precision', $value, $nameKey); |
57
|
|
|
} |
58
|
|
|
}); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Validate value os an integer |
63
|
|
|
* |
64
|
|
|
* @return $this |
65
|
|
|
*/ |
66
|
|
|
public function isInt() |
67
|
|
|
{ |
68
|
|
|
return $this->add(function($value, $nameKey) { |
69
|
|
|
if (!is_int($value)) { |
70
|
|
|
return $this->createError('number.is_int', $value, $nameKey); |
71
|
|
|
} |
72
|
|
|
}); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Validate value is a float |
77
|
|
|
* |
78
|
|
|
* @return $this |
79
|
|
|
*/ |
80
|
|
|
public function isFloat() |
81
|
|
|
{ |
82
|
|
|
return $this->add(function($value, $nameKey) { |
83
|
|
|
if (!is_float($value)) { |
84
|
|
|
return $this->createError('number.is_float', $value, $nameKey); |
85
|
|
|
} |
86
|
|
|
}); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* Validate value is numeric, be it float or int. |
91
|
|
|
* |
92
|
|
|
* @return $this |
93
|
|
|
*/ |
94
|
|
|
public function isNumber() |
95
|
|
|
{ |
96
|
|
|
return $this->add(function($value, $nameKey) { |
97
|
|
|
if (!is_numeric($value)) { |
98
|
|
|
return $this->createError('number.is_numeric', $value, $nameKey); |
99
|
|
|
} |
100
|
|
|
}); |
101
|
|
|
} |
102
|
|
|
} |