Completed
Pull Request — master (#175)
by
unknown
02:25 queued 02:25
created

InRange   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 41
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validateValue() 0 9 2
A getOptions() 0 7 1
A __construct() 0 18 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Yiisoft\Validator\FormatterInterface;
9
use Yiisoft\Validator\ValidationContext;
10
use Yiisoft\Arrays\ArrayHelper;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
14
/**
15
 * Validates that the value is among a list of values.
16
 *
17
 * The range can be specified via constructor.
18
 * If the {@see InRange::$not} is called, the rule will ensure the value is NOT among the specified range.
19
 */
20
#[Attribute(Attribute::TARGET_PROPERTY)]
21
final class InRange extends Rule
22
{
23 8
    public function __construct(
24
        private iterable $range,
25
        /**
26
         * @var bool whether the comparison is strict (both type and value must be the same)
27
         */
28
        private bool $strict = false,
29
        /**
30
         * @var bool whether to invert the validation logic. Defaults to false. If set to `true`, the value should NOT
31
         * be among the list of values passed via constructor.
32
         */
33
        private bool $not = false,
34
        private string $message = 'This value is invalid.',
35
        ?FormatterInterface $formatter = null,
36
        bool $skipOnEmpty = false,
37
        bool $skipOnError = false,
38
        $when = null
39
    ) {
40 8
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
41
    }
42
43 8
    protected function validateValue($value, ?ValidationContext $context = null): Result
44
    {
45 8
        $result = new Result();
46
47 8
        if ($this->not === ArrayHelper::isIn($value, $this->range, $this->strict)) {
48 7
            $result->addError($this->formatMessage($this->message));
49
        }
50
51 8
        return $result;
52
    }
53
54 3
    public function getOptions(): array
55
    {
56 3
        return array_merge(parent::getOptions(), [
57 3
            'range' => $this->range,
58 3
            'strict' => $this->strict,
59 3
            'not' => $this->not,
60 3
            'message' => $this->formatMessage($this->message),
61
        ]);
62
    }
63
}
64