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\Domain\BooleanValidation; |
7
|
|
|
use AmmitPhp\Ammit\UI\Resolver\UIValidationEngine; |
8
|
|
|
use AmmitPhp\Ammit\UI\Resolver\Validator\UIValidatorInterface; |
9
|
|
|
|
10
|
|
|
trait BooleanValidatorTrait |
11
|
|
|
{ |
12
|
|
|
/** @var UIValidationEngine */ |
13
|
|
|
protected $validationEngine; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Exceptions are caught in order to be processed later |
17
|
|
|
* @param mixed $value Boolean ? |
18
|
|
|
* |
19
|
|
|
* @return boolean|null Value casted into boolean or null |
20
|
|
|
*/ |
21
|
|
View Code Duplication |
public function mustBeBooleanOrEmpty($value, string $propertyPath = null, UIValidatorInterface $parentValidator = null, string $exceptionMessage = null) |
|
|
|
|
22
|
|
|
{ |
23
|
|
|
if ($value === '') { |
24
|
|
|
return null; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return $this->mustBeBoolean($value, $propertyPath, $parentValidator, $exceptionMessage); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Exceptions are caught in order to be processed later |
32
|
|
|
* @param mixed $value Boolean ? |
33
|
|
|
* |
34
|
|
|
* @return boolean Value casted into boolean or false |
35
|
|
|
*/ |
36
|
|
|
public function mustBeBoolean($value, string $propertyPath = null, UIValidatorInterface $parentValidator = null, string $exceptionMessage = null): bool |
37
|
|
|
{ |
38
|
1 |
|
$this->validationEngine->validateFieldValue( |
39
|
1 |
|
$parentValidator ?: $this, |
40
|
1 |
View Code Duplication |
function() use ($value, $propertyPath, $exceptionMessage) { |
|
|
|
|
41
|
1 |
|
$booleanValidation = new BooleanValidation(); |
42
|
1 |
|
if ($booleanValidation->isBooleanValid($value)) { |
43
|
1 |
|
return; |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
if (null === $exceptionMessage) { |
47
|
|
|
$exceptionMessage = sprintf( |
|
|
|
|
48
|
|
|
'Value "%s" is not a boolean.', |
49
|
|
|
$value |
50
|
|
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
throw new InvalidArgumentException( |
54
|
|
|
$exceptionMessage, |
55
|
1 |
|
0, |
56
|
|
|
$propertyPath, |
57
|
|
|
$value |
58
|
|
|
); |
59
|
1 |
|
} |
60
|
|
|
); |
61
|
|
|
|
62
|
|
|
// Otherwise "false" would return true |
63
|
1 |
|
if (in_array($value, [true, 'true', '1', 1], true)) { |
|
|
|
|
64
|
1 |
|
return true; |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
return false; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
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.