1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace mindplay\kissform\Fields; |
4
|
|
|
|
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use mindplay\kissform\Fields\Base\NumericField; |
7
|
|
|
use mindplay\kissform\InputModel; |
8
|
|
|
use mindplay\kissform\InputRenderer; |
9
|
|
|
use mindplay\kissform\Validators\CheckFloat; |
10
|
|
|
use UnexpectedValueException; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* This class provides information about a floating point field. |
14
|
|
|
*/ |
15
|
|
View Code Duplication |
class FloatField extends NumericField |
|
|
|
|
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* {@inheritdoc} |
19
|
|
|
*/ |
20
|
1 |
|
public function renderInput(InputRenderer $renderer, InputModel $model, array $attr) |
21
|
|
|
{ |
22
|
1 |
|
$pattern = $this->min_value === null || $this->min_value < 0 |
23
|
1 |
|
? '-?\d*(\.(?=\d))?\d*' // accept negative |
24
|
1 |
|
: '\d*(\.(?=\d))?\d*'; |
25
|
|
|
|
26
|
1 |
|
return parent::renderInput($renderer, $model, $attr + ['pattern' => $pattern]); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param InputModel $model |
31
|
|
|
* |
32
|
|
|
* @return float|null |
33
|
|
|
* |
34
|
|
|
* @throws UnexpectedValueException if unable to parse the input |
35
|
|
|
*/ |
36
|
|
|
public function getValue(InputModel $model) |
37
|
|
|
{ |
38
|
|
|
$input = $model->getInput($this); |
39
|
|
|
|
40
|
|
|
if ($input === null) { |
41
|
|
|
return null; // no input available |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if (is_numeric($input)) { |
45
|
|
|
return (float) $input; |
|
|
|
|
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
throw new UnexpectedValueException("unexpected input: {$input}"); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param InputModel $model |
53
|
|
|
* @param float|null $value |
54
|
|
|
* |
55
|
|
|
* @return void |
56
|
|
|
* |
57
|
|
|
* @throws InvalidArgumentException if the given value is unacceptable. |
58
|
|
|
*/ |
59
|
|
|
public function setValue(InputModel $model, $value) |
60
|
|
|
{ |
61
|
|
|
if (is_numeric($value)) { |
62
|
|
|
$model->setInput($this, (string) $value); |
63
|
|
|
} elseif ($value === null) { |
64
|
|
|
$model->setInput($this, null); |
65
|
|
|
} else { |
66
|
|
|
throw new InvalidArgumentException("unexpected value type: " . gettype($value)); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @inheritdoc |
72
|
|
|
*/ |
73
|
1 |
|
protected function createTypeValidator() |
74
|
|
|
{ |
75
|
1 |
|
return new CheckFloat(); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.