1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Albert221\Validation\Rule; |
6
|
|
|
|
7
|
|
|
use Albert221\Validation\Rule; |
8
|
|
|
use Albert221\Validation\RuleValidator; |
9
|
|
|
use Albert221\Validation\Verdict; |
10
|
|
|
use Albert221\Validation\VerdictInterface; |
11
|
|
|
use InvalidArgumentException; |
12
|
|
|
|
13
|
|
|
class LengthValidator extends RuleValidator |
14
|
|
|
{ |
15
|
9 |
|
public function verdict($value, Rule $rule): VerdictInterface |
16
|
|
|
{ |
17
|
9 |
|
$this->validateOptions($rule->getOptions()); |
18
|
|
|
|
19
|
6 |
|
if (is_null($value)) { |
20
|
4 |
|
return Verdict::passing($rule); |
21
|
|
|
} |
22
|
|
|
|
23
|
6 |
|
return Verdict::create( |
24
|
6 |
|
$this->isNotSmallerThanItShould($value, $rule) |
25
|
6 |
|
&& $this->isNotBiggerThanItShould($value, $rule) |
26
|
6 |
|
&& $this->isExactlyHowItShould($value, $rule), |
27
|
6 |
|
$rule |
28
|
|
|
); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param $value |
33
|
|
|
* @param Rule $rule |
34
|
|
|
* |
35
|
|
|
* @return bool |
36
|
|
|
*/ |
37
|
6 |
|
private function isNotSmallerThanItShould($value, Rule $rule): bool |
38
|
|
|
{ |
39
|
6 |
|
return mb_strlen($value) >= $rule->getOption('min', 0); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param $value |
44
|
|
|
* @param Rule $rule |
45
|
|
|
* |
46
|
|
|
* @return bool |
47
|
|
|
*/ |
48
|
5 |
|
private function isNotBiggerThanItShould($value, Rule $rule): bool |
49
|
|
|
{ |
50
|
5 |
|
return mb_strlen($value) <= $rule->getOption('max', PHP_INT_MAX); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param $value |
55
|
|
|
* @param Rule $rule |
56
|
|
|
* |
57
|
|
|
* @return bool |
58
|
|
|
*/ |
59
|
5 |
|
private function isExactlyHowItShould($value, Rule $rule): bool |
60
|
|
|
{ |
61
|
5 |
|
return is_null($rule->getOption('exact')) |
62
|
5 |
|
|| mb_strlen($value) === $rule->getOption('exact'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param array $options |
67
|
|
|
*/ |
68
|
9 |
|
private function validateOptions(array $options) |
69
|
|
|
{ |
70
|
9 |
|
if (isset($options['min']) && isset($options['max'])) { |
71
|
3 |
|
if ($options['min'] == $options['max']) { |
72
|
1 |
|
throw new InvalidArgumentException( |
73
|
1 |
|
'Value of "min" and "max" must not be the same. Use "exact" option instead.' |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
|
77
|
2 |
|
if ($options['min'] > $options['max']) { |
78
|
1 |
|
throw new InvalidArgumentException( |
79
|
1 |
|
'Value of "max" option must be bigger than value of "min" option.' |
80
|
|
|
); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
7 |
|
if ((isset($options['min']) || isset($options['max'])) && isset($options['exact'])) { |
85
|
1 |
|
throw new InvalidArgumentException( |
86
|
1 |
|
'If "exact" option has been passed, no other options must be passed.' |
87
|
|
|
); |
88
|
|
|
} |
89
|
6 |
|
} |
90
|
|
|
} |
91
|
|
|
|