Passed
Push — master ( 9d8a75...f0a095 )
by Alexander
01:39
created

InRange::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

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