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\CheckInt; |
10
|
|
|
use UnexpectedValueException; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* This class provides information about an integer field. |
14
|
|
|
* |
15
|
|
|
* TODO extract into NumericField base class with $allow_float property, refactor validation, adjust HTML5 attributes |
16
|
|
|
*/ |
17
|
|
View Code Duplication |
class IntField extends NumericField |
|
|
|
|
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* {@inheritdoc} |
21
|
|
|
*/ |
22
|
1 |
|
public function renderInput(InputRenderer $renderer, InputModel $model, array $attr) |
23
|
|
|
{ |
24
|
1 |
|
$pattern = $this->min_value === null || $this->min_value < 0 |
25
|
1 |
|
? '-?\d*' // accept negative |
26
|
1 |
|
: '\d*'; |
27
|
|
|
|
28
|
1 |
|
return parent::renderInput($renderer, $model, $attr + ['pattern' => $pattern]); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param InputModel $model |
33
|
|
|
* |
34
|
|
|
* @return int|null |
35
|
|
|
* |
36
|
|
|
* @throws UnexpectedValueException if unable to parse the input |
37
|
|
|
*/ |
38
|
1 |
|
public function getValue(InputModel $model) |
39
|
|
|
{ |
40
|
1 |
|
$input = $model->getInput($this); |
41
|
|
|
|
42
|
1 |
|
if ($input === null) { |
43
|
1 |
|
return null; // no input available |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
if (is_numeric($input)) { |
47
|
1 |
|
return (int) $input; |
|
|
|
|
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
throw new UnexpectedValueException("unexpected input: {$input}"); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param InputModel $model |
55
|
|
|
* @param int|null $value |
56
|
|
|
* |
57
|
|
|
* @return void |
58
|
|
|
* |
59
|
|
|
* @throws InvalidArgumentException if the given value is unacceptable. |
60
|
|
|
*/ |
61
|
1 |
|
public function setValue(InputModel $model, $value) |
62
|
|
|
{ |
63
|
1 |
|
if (is_int($value)) { |
64
|
1 |
|
$model->setInput($this, (string) $value); |
65
|
1 |
|
} elseif ($value === null) { |
66
|
1 |
|
$model->setInput($this, null); |
67
|
|
|
} else { |
68
|
1 |
|
throw new InvalidArgumentException("unexpected value type: " . gettype($value)); |
69
|
|
|
} |
70
|
1 |
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @inheritdoc |
74
|
|
|
*/ |
75
|
2 |
|
protected function createTypeValidator() |
76
|
|
|
{ |
77
|
2 |
|
return new CheckInt(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
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.