Completed
Push — master ( dc27cd...c0eb3b )
by Rasmus
07:46
created

CheckSelected   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 100 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 38
loc 38
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 5 5 1
B validate() 15 15 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 1
                $field,
50 1
                $this->error ?: lang::text("mindplay/kissform", "selected", ["field" => $validation->getLabel($field)])
51
            );
52
        }
53 1
    }
54
}
55