Passed
Pull Request — master (#119)
by
unknown
03:21 queued 01:19
created

Subset::validateValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.1406

Importance

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