1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace AmmitPhp\Ammit\UI\Resolver\Validator\Implementation\Pure; |
4
|
|
|
|
5
|
|
|
use AmmitPhp\Ammit\UI\Resolver\Validator\InvalidArgumentException; |
6
|
|
|
use AmmitPhp\Ammit\UI\Resolver\UIValidationEngine; |
7
|
|
|
use AmmitPhp\Ammit\UI\Resolver\Validator\UIValidatorInterface; |
8
|
|
|
|
9
|
|
|
trait IntegerValidatorTrait |
10
|
|
|
{ |
11
|
|
|
/** @var UIValidationEngine */ |
12
|
|
|
protected $validationEngine; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Exceptions are caught in order to be processed later |
16
|
|
|
* @param mixed $value Integer ? |
17
|
|
|
* |
18
|
|
|
* @return int|null Value casted into int or -1 or null |
19
|
|
|
*/ |
20
|
|
View Code Duplication |
public function mustBeIntegerOrEmpty($value, string $propertyPath = null, UIValidatorInterface $parentValidator = null, string $exceptionMessage = null) |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
if ($value === '') { |
23
|
|
|
return null; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
return $this->mustBeInteger($value, $propertyPath, $parentValidator, $exceptionMessage); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Exceptions are caught in order to be processed later |
31
|
|
|
* @param mixed $value Integer ? |
32
|
|
|
* |
33
|
|
|
* @return int Value casted into int or -1 |
34
|
|
|
*/ |
35
|
|
View Code Duplication |
public function mustBeInteger($value, string $propertyPath = null, UIValidatorInterface $parentValidator = null, string $exceptionMessage = null): int |
|
|
|
|
36
|
|
|
{ |
37
|
1 |
|
if (is_numeric($value)) { |
38
|
1 |
|
$value = (int) $value; |
39
|
|
|
} |
40
|
|
|
|
41
|
1 |
|
$this->validationEngine->validateFieldValue( |
42
|
1 |
|
$parentValidator ?: $this, |
43
|
1 |
|
function() use ($value, $propertyPath, $exceptionMessage) { |
44
|
1 |
|
if (is_int($value)) { |
45
|
1 |
|
return; |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
if (null === $exceptionMessage) { |
49
|
|
|
$exceptionMessage = sprintf( |
|
|
|
|
50
|
|
|
'Value "%s" is not an integer.', |
51
|
|
|
$value |
52
|
|
|
); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
throw new InvalidArgumentException( |
56
|
|
|
$exceptionMessage, |
57
|
1 |
|
0, |
58
|
|
|
$propertyPath, |
59
|
|
|
$value |
60
|
|
|
); |
61
|
1 |
|
} |
62
|
|
|
); |
63
|
|
|
|
64
|
1 |
|
if (!is_int($value)) { |
65
|
1 |
|
return -1; |
66
|
|
|
} |
67
|
|
|
|
68
|
1 |
|
return $value; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
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.