Passed
Pull Request — master (#222)
by Dmitriy
02:23
created

InRangeHandler::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 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.6111
cc 5
nc 4
nop 3
crap 5
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\ValidationContext;
10
use Yiisoft\Validator\ValidatorInterface;
11
use Yiisoft\Validator\Exception\UnexpectedRuleException;
12
13
/**
14
 * Validates that the value is among a list of values.
15
 *
16
 * The range can be specified via constructor.
17
 * If the {@see InRange::$not} is called, the rule will ensure the value is NOT among the specified range.
18
 */
19
final class InRangeHandler implements RuleHandlerInterface
20
{
21 32
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
22
    {
23 32
        if (!$rule instanceof InRange) {
24 1
            throw new UnexpectedRuleException(InRange::class, $rule);
25
        }
26
27 31
        $result = new Result();
28
29 31
        if ($rule->skipOnEmpty && $value === null) {
30 1
            return $result;
31
        }
32
33 30
        if ($rule->not === ArrayHelper::isIn($value, $rule->range, $rule->strict)) {
34 18
            $result->addError($rule->message);
35
        }
36
37 30
        return $result;
38
    }
39
}
40