Passed
Pull Request — master (#65)
by Alexander
27:54 queued 12:56
created

InRange::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\HasValidationMessage;
8
use Yiisoft\Validator\Rule;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\DataSetInterface;
12
13
/**
14
 * In validates that the attribute value is among a list of values.
15
 *
16
 * The range can be specified via the [[range]] property.
17
 * If the [[not]] property is set true, the validator will ensure the attribute value
18
 * is NOT among the specified range.
19
 *
20
 */
21
class InRange extends Rule
22
{
23
    use HasValidationMessage;
24
25
    /**
26
     * @var array|\Traversable
27
     */
28
    private $range;
29
    /**
30
     * @var bool whether the comparison is strict (both type and value must be the same)
31
     */
32
    private bool $strict = false;
33
    /**
34
     * @var bool whether to invert the validation logic. Defaults to false. If set to true,
35
     * the attribute value should NOT be among the list of values defined via [[range]].
36
     */
37
    private bool $not = false;
38 8
39
    private string $message = 'This value is invalid.';
40 8
41 1
    public function __construct($range)
42
    {
43
        if (!is_array($range) && !($range instanceof \Traversable)) {
44 7
            throw new \RuntimeException('The "range" property must be set.');
45
        }
46
47 7
        $this->range = $range;
48
    }
49 7
50
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
51
    {
52 7
        $in = false;
53 7
54
        if (
55 3
            ($value instanceof \Traversable || is_array($value)) &&
56
            ArrayHelper::isSubset($value, $this->range, $this->strict)
57
        ) {
58 7
            $in = true;
59 4
        }
60
61
        if (!$in && ArrayHelper::isIn($value, $this->range, $this->strict)) {
62 7
            $in = true;
63
        }
64 7
65 6
        $result = new Result();
66
67
        if ($this->not === $in) {
68 7
            $result->addError($this->translateMessage($this->message));
69
        }
70
71 2
        return $result;
72
    }
73 2
74 2
    public function strict(): self
75 2
    {
76
        $new = clone $this;
77
        $new->strict = true;
78 1
        return $new;
79
    }
80 1
81 1
    public function not(): self
82 1
    {
83
        $new = clone $this;
84
        $new->not = true;
85
        return $new;
86
    }
87
}
88