Completed
Push — master ( abf834...d5d973 )
by Rasmus
03:09
created

CheckParser::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 6
nc 3
nop 3
crap 3
1
<?php
2
3
namespace mindplay\kissform\Validators;
4
5
use mindplay\kissform\Facets\FieldInterface;
6
use mindplay\kissform\Facets\ParserInterface;
7
use mindplay\kissform\Facets\ValidatorInterface;
8
use mindplay\kissform\InputModel;
9
use mindplay\kissform\InputValidation;
10
use mindplay\lang;
11
12
/**
13
 * Validate a Field by attempting to parse the input value.
14
 *
15
 * This is useful for e.g. date or date/time input which may be parsed by {@see DateTimeStringField}.
16
 */
17
class CheckParser implements ValidatorInterface
18
{
19
    /**
20
     * @var ParserInterface
21
     */
22
    private $parser;
23
24
    /**
25
     * @var string
26
     */
27
    private $error;
28
29
    /**
30
     * @param ParserInterface $parser the InputParser (usually a Field) which should attempt to parse the input
31
     * @param string          $error  error message template (the "{field}" token will be substituted)
32
     */
33 3
    public function __construct(ParserInterface $parser, $error)
34
    {
35 3
        $this->parser = $parser;
36 3
        $this->error = $error;
37 3
    }
38
39 1
    public function validate(FieldInterface $field, InputModel $model, InputValidation $validation)
40
    {
41 1
        $input = $model->getInput($field);
42
43 1
        if ($input === null) {
44 1
            return; // no input
45
        }
46
47 1
        if ($this->parser->parseInput($input) === null) {
0 ignored issues
show
Bug introduced by
It seems like $input defined by $model->getInput($field) on line 41 can also be of type array; however, mindplay\kissform\Facets...Interface::parseInput() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
48 1
            $model->setError($field, strtr($this->error, ["field" => $validation->getLabel($field)]));
49
        }
50 1
    }
51
}
52