Passed
Pull Request — master (#119)
by
unknown
07:17
created

Subset::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 2
rs 10
1
<?php
2
3
namespace Yiisoft\Validator\Rule;
4
5
use Yiisoft\Arrays\ArrayHelper;
6
use Yiisoft\Validator\Result;
7
use Yiisoft\Validator\Rule;
8
use Yiisoft\Validator\ValidationContext;
9
10
class Subset extends Rule
11
{
12
    /**
13
     * @var iterable
14
     */
15
    private iterable $range;
16
    /**
17
     * @var bool whether the comparison is strict (both type and value must be the same)
18
     */
19
    private bool $strict = false;
20
21
    private string $iterableMessage = 'Value must be iterable';
22
23
    private string $subsetMessage = 'Value must be subset of...';
24
25 4
    public function __construct(iterable $range)
26
    {
27 4
        $this->range = $range;
28 4
    }
29
30 3
    protected function validateValue($value, ValidationContext $context = null): Result
31
    {
32 3
        $result = new Result();
33
34 3
        if (!is_iterable($value)) {
35
            $result->addError($this->formatMessage($this->iterableMessage));
36
            return $result;
37
        }
38
39 3
        if (!ArrayHelper::isSubset($value, $this->range, $this->strict)) {
40 1
            $result->addError($this->formatMessage($this->subsetMessage));
41
        }
42
43 3
        return $result;
44
    }
45
46
    public function strict(): self
47
    {
48
        $new = clone $this;
49
        $new->strict = true;
50
        return $new;
51
    }
52
53
    public function getOptions(): array
54
    {
55
        return array_merge(
56
            parent::getOptions(),
57
            [
58
                'iterableMessage' => $this->formatMessage($this->iterableMessage),
59
                'subsetMessage' => $this->formatMessage($this->subsetMessage),
60
                'range' => $this->range,
61
                'strict' => $this->strict
62
            ],
63
        );
64
    }
65
}
66