-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathNumberField.php
More file actions
100 lines (85 loc) · 2.16 KB
/
NumberField.php
File metadata and controls
100 lines (85 loc) · 2.16 KB
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
<?php
namespace Gregwar\Formidable\Fields;
/**
* Number
*
* @author Grégoire Passault <g.passault@gmail.com>
*/
class NumberField extends Field
{
/**
* Field type
*/
protected $type = 'number';
/**
* Minimal value
*/
protected $min = null;
/**
* Maximum value
*/
protected $max = null;
/**
* Step
*/
protected $step = 'any';
public function __construct()
{
$this->attributes['step'] = $this->step;
}
public function __sleep()
{
return array_merge(parent::__sleep(), array(
'min', 'max', 'step'
));
}
public function push($name, $value = null)
{
switch ($name) {
case 'min':
$this->min = $value;
$this->attributes['min'] = $value;
break;
case 'max':
$this->max = $value;
$this->attributes['max'] = $value;
break;
case 'step':
$this->step = $value;
$this->attributes['step'] = $value;
break;
}
parent::push($name, $value);
}
public function check()
{
if (!$this->required && !$this->value) {
return;
}
if ($error = parent::check()) {
return $error;
}
if (!is_numeric($this->value)) {
return array('number', $this->printName());
}
if ($this->min !== null) {
if ($this->value < $this->min) {
return array('number_min', $this->printName(), $this->min);
}
}
if ($this->max !== null) {
if ($this->value > $this->max) {
return array('number_max', $this->printName(), $this->max);
}
}
if ($this->step != 'any') {
$step = abs((float)$this->step);
$value = abs((float)$this->value);
$factor = round($value/$step)*$step;
$delta = $value-$factor;
if ($delta > 0.00001) {
return array('number_step', $this->printName(), $this->step);
}
}
}
}