Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
20 / 20 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
StrLen | |
100.00% |
20 / 20 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
validate | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
4 |
1 | <?php |
2 | |
3 | namespace Verja\Validator; |
4 | |
5 | use Verja\Error; |
6 | use Verja\Validator; |
7 | |
8 | class StrLen extends Validator |
9 | { |
10 | /** @var int */ |
11 | protected $min; |
12 | |
13 | /** @var int */ |
14 | protected $max; |
15 | |
16 | /** |
17 | * StrLen constructor. |
18 | * |
19 | * @param int $min |
20 | * @param int $max |
21 | */ |
22 | public function __construct(int $min, int $max = 0) |
23 | { |
24 | $this->min = $min; |
25 | $this->max = $max; |
26 | } |
27 | |
28 | |
29 | /** {@inheritdoc} */ |
30 | public function validate($value, array $context = []): bool |
31 | { |
32 | $strLen = strlen($value); |
33 | if ($strLen < $this->min) { |
34 | $this->error = new Error( |
35 | 'STRLEN_TOO_SHORT', |
36 | $value, |
37 | sprintf('value should be at least %d characters long', $this->min), |
38 | [ 'min' => $this->min, 'max' => $this->max ] |
39 | ); |
40 | return false; |
41 | } elseif ($this->max > 0 && $strLen > $this->max) { |
42 | $this->error = new Error( |
43 | 'STRLEN_TOO_LONG', |
44 | $value, |
45 | sprintf('value should be maximal %d characters long', $this->max), |
46 | [ 'min' => $this->min, 'max' => $this->max ] |
47 | ); |
48 | return false; |
49 | } |
50 | |
51 | return true; |
52 | } |
53 | } |