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

CheckSelected::validate()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 15
Ratio 100 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

Changes 0
Metric Value
dl 15
loc 15
ccs 8
cts 9
cp 0.8889
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 3
nop 3
crap 5.0342
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 selection from a list of allowed values (for drop-down inputs, radio lists, etc.)
13
 *
14
 * This will automatically respect {@link Field::$required} so there is no need to manually
15
 * validate as required() beforehand.
16
 */
17 View Code Duplication
class CheckSelected implements ValidatorInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
18
{
19
    /**
20
     * @var string[]|null
21
     */
22
    private $options;
23
24
    /**
25
     * @var string|null
26
     */
27
    private $error;
28
29
    /**
30
     * @param string[]|null $options list of allowed values
31
     * @param string|null   $error   optional custom error message
32
     */
33 4
    public function __construct(array $options, $error = null)
34
    {
35 4
        $this->options = $options;
36 4
        $this->error = $error;
37 4
    }
38
39 1
    public function validate(FieldInterface $field, InputModel $model, InputValidation $validation)
40
    {
41 1
        $input = $model->getInput($field);
42
43 1
        if (($field->isRequired() === false) && ($input === null)) {
44 1
            return; // no input, not required
45
        }
46
47 1
        if (! in_array($input, $this->options)) {
48 1
            $model->setError(
49
                $field,
50 1
                $this->error ?: lang::text("mindplay/kissform", "selected", ["field" => $validation->getLabel($field)])
51
            );
52
        }
53 1
    }
54
}
55