Passed
Pull Request — master (#222)
by Alexander
04:51 queued 02:32
created

InRangeValidator::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.6111
cc 5
nc 4
nop 4
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\InRange;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\RuleValidatorInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
use Yiisoft\Validator\Exception\UnexpectedRuleException;
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
final class InRangeValidator implements RuleValidatorInterface
21
{
22 32
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
23
    {
24 32
        if (!$rule instanceof InRange) {
25 1
            throw new UnexpectedRuleException(InRange::class, $rule);
26
        }
27
28 31
        $result = new Result();
29
30 31
        if ($rule->skipOnEmpty && $value === null) {
31 1
            return $result;
32
        }
33
34 30
        if ($rule->not === ArrayHelper::isIn($value, $rule->range, $rule->strict)) {
35 18
            $result->addError($rule->message);
36
        }
37
38 30
        return $result;
39
    }
40
}
41