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 StringValidatorTrait |
10
|
|
|
{ |
11
|
|
|
/** @var UIValidationEngine */ |
12
|
|
|
protected $validationEngine; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Exceptions are caught in order to be processed later |
16
|
|
|
* @param mixed $value String ? |
17
|
|
|
* |
18
|
|
|
* @return string|null Casted to string or null |
19
|
|
|
*/ |
20
|
|
View Code Duplication |
public function mustBeStringOrEmpty($value, string $propertyPath = null, UIValidatorInterface $parentValidator = null, string $exceptionMessage = null) |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
if (empty($value)) { |
23
|
|
|
return null; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
return $this->mustBeString($value, $propertyPath, $parentValidator, $exceptionMessage); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Exceptions are caught in order to be processed later |
31
|
|
|
* @param mixed $value String ? |
32
|
|
|
* |
33
|
|
|
* @return string Casted to string |
34
|
|
|
*/ |
35
|
|
|
public function mustBeString($value, string $propertyPath = null, UIValidatorInterface $parentValidator = null, string $exceptionMessage = null): string |
36
|
|
|
{ |
37
|
1 |
|
$this->validationEngine->validateFieldValue( |
38
|
1 |
|
$parentValidator ?: $this, |
39
|
1 |
|
function() use ($value, $propertyPath, $exceptionMessage) { |
40
|
1 |
|
if (is_string($value)) { |
41
|
1 |
|
return; |
42
|
|
|
} |
43
|
|
|
|
44
|
1 |
|
if (null === $exceptionMessage) { |
45
|
|
|
$exceptionMessage = sprintf( |
|
|
|
|
46
|
|
|
'Value "%s" is not a string.', |
47
|
|
|
$value |
48
|
|
|
); |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
throw new InvalidArgumentException( |
52
|
|
|
$exceptionMessage, |
53
|
1 |
|
0, |
54
|
|
|
$propertyPath, |
55
|
|
|
$value |
56
|
|
|
); |
57
|
1 |
|
} |
58
|
|
|
); |
59
|
|
|
|
60
|
1 |
|
if (null === $value || !is_string($value)) { |
61
|
1 |
|
return ''; |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
return (string) $value; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
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.