Completed
Push — master ( 6f059f...dc27cd )
by Rasmus
05:49
created

CheckLength   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 93.33%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 47
ccs 14
cts 15
cp 0.9333
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B validate() 0 17 5
1
<?php
2
3
namespace mindplay\kissform\Validators;
4
5
use mindplay\kissform\Facets\FieldInterface;
6
use mindplay\kissform\Facets\ValidatorInterface;
7
use mindplay\kissform\InputModel;
8
use mindplay\kissform\InputValidation;
9
use mindplay\lang;
10
11
/**
12
 * Validate min/max length of a string.
13
 */
14
class CheckLength implements ValidatorInterface
15
{
16
    /**
17
     * @var string|null
18
     */
19
    private $error;
20
21
    /**
22
     * @var int
23
     */
24
    private $min;
25
26
    /**
27
     * @var int
28
     */
29
    private $max;
30
31
    /**
32
     * @param int         $min   min. length
33
     * @param int         $max   max. length
34
     * @param string|null $error optional custom error message
35
     */
36 8
    public function __construct($min, $max, $error = null)
37
    {
38 8
        $this->error = $error;
39 8
        $this->min = $min;
40 8
        $this->max = $max;
41 8
    }
42
43 1
    public function validate(FieldInterface $field, InputModel $model, InputValidation $validation)
44
    {
45 1
        $input = $model->getInput($field);
46
47 1
        if ($input === null) {
48 1
            return; // no input given
49
        }
50
51 1
        $length = mb_strlen($input);
52
53 1
        if ($length < $this->min || $length > $this->max) {
54 1
            $model->setError(
55
                $field,
56 1
                $this->error ?: lang::text("mindplay/kissform", "length", ["field" => $validation->getLabel($field), "min" => $this->min, "max" => $this->max])
57
            );
58
        }
59 1
    }
60
}
61