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

CheckMaxLength::validate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 9
cts 10
cp 0.9
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 3
crap 4.016
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 maximum length of a string.
13
 */
14
class CheckMaxLength implements ValidatorInterface
15
{
16
    /**
17
     * @var string|null
18
     */
19
    private $error;
20
21
    /**
22
     * @var int
23
     */
24
    private $max;
25
26
    /**
27
     * @param int         $max   max. length
28
     * @param string|null $error optional custom error message
29
     */
30 8
    public function __construct($max, $error = null)
31
    {
32 8
        $this->error = $error;
33 8
        $this->max = $max;
34 8
    }
35
36 1
    public function validate(FieldInterface $field, InputModel $model, InputValidation $validation)
37
    {
38 1
        $input = $model->getInput($field);
39
40 1
        if ($input === null) {
41 1
            return; // no input
42
        }
43
44 1
        $length = mb_strlen($input);
45
46 1
        if ($length > $this->max) {
47 1
            $model->setError(
48
                $field,
49 1
                $this->error ?: lang::text("mindplay/kissform", "maxLength", ["field" => $validation->getLabel($field), "max" => $this->max])
50
            );
51
        }
52 1
    }
53
}
54