|
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::create(true, $rule); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
6 |
|
return Verdict::create( |
|
24
|
6 |
|
mb_strlen($value) >= $rule->getOption('min', 0) |
|
25
|
6 |
|
&& mb_strlen($value) <= $rule->getOption('max', PHP_INT_MAX) |
|
26
|
|
|
&& ( |
|
27
|
5 |
|
is_null($rule->getOption('exact')) |
|
28
|
6 |
|
|| mb_strlen($value) === $rule->getOption('exact') |
|
29
|
|
|
), |
|
30
|
6 |
|
$rule |
|
31
|
|
|
); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param array $options |
|
36
|
|
|
*/ |
|
37
|
9 |
|
private function validateOptions(array $options) |
|
38
|
|
|
{ |
|
39
|
9 |
|
if (isset($options['min']) && isset($options['max'])) { |
|
40
|
3 |
|
if ($options['min'] == $options['max']) { |
|
41
|
1 |
|
throw new InvalidArgumentException( |
|
42
|
1 |
|
'Value of "min" and "max" must not be the same. Use "exact" option instead.' |
|
43
|
|
|
); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
2 |
|
if ($options['min'] > $options['max']) { |
|
47
|
1 |
|
throw new InvalidArgumentException( |
|
48
|
1 |
|
'Value of "max" option must be bigger than value of "min" option.' |
|
49
|
|
|
); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
7 |
|
if ((isset($options['min']) || isset($options['max'])) && isset($options['exact'])) { |
|
54
|
1 |
|
throw new InvalidArgumentException( |
|
55
|
1 |
|
'If "exact" option has been passed, no other options must be passed.' |
|
56
|
|
|
); |
|
57
|
|
|
} |
|
58
|
6 |
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|