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

InRange   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 67
ccs 21
cts 24
cp 0.875
rs 10
wmc 13

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 3
A not() 0 4 1
B validateValue() 0 22 7
A message() 0 4 1
A strict() 0 4 1
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