Test Failed
Pull Request — master (#175)
by
unknown
05:56 queued 03:39
created

InRange::not()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
 * In validates that the attribute 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 validator will ensure the attribute value
19
 * is NOT among the specified range.
20
 */
21
#[Attribute(Attribute::TARGET_PROPERTY)]
22
final class InRange extends Rule
23
{
24
    public function __construct(
25
        private iterable $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 passed via constructor.
33
         */
34
        private bool $not = false,
35
        private string $message = 'This value is invalid.',
36
        ?FormatterInterface $formatter = null,
37
        bool $skipOnEmpty = false,
38
        bool $skipOnError = false,
39
        $when = null
40 8
    ) {
41
        parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when);
42 8
    }
43 8
44 8
    protected function validateValue($value, ?ValidationContext $context = null): Result
45
    {
46
        $result = new Result();
47 8
48
        if ($this->not === ArrayHelper::isIn($value, $this->range, $this->strict)) {
49 8
            $result->addError($this->formatMessage($this->message));
50
        }
51 8
52 7
        return $result;
53
    }
54
55 8
    public function getOptions(): array
56
    {
57
        return array_merge(parent::getOptions(), [
58 2
            'range' => $this->range,
59
            'strict' => $this->strict,
60 2
            'not' => $this->not,
61 2
            'message' => $this->formatMessage($this->message),
62 2
        ]);
63
    }
64
}
65