Passed
Pull Request — master (#222)
by Dmitriy
02:35
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\Exception\UnexpectedRuleException;
11
12
/**
13
 * Validates that the value is among a list of values.
14
 *
15
 * The range can be specified via constructor.
16
 * If the {@see InRange::$not} is called, the rule will ensure the value is NOT among the specified range.
17
 */
18
final class InRangeHandler implements RuleHandlerInterface
19
{
20 32
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
21
    {
22 32
        if (!$rule instanceof InRange) {
23 1
            throw new UnexpectedRuleException(InRange::class, $rule);
24
        }
25
26 31
        $result = new Result();
27
28 31
        if ($rule->skipOnEmpty && $value === null) {
29 1
            return $result;
30
        }
31
32 30
        if ($rule->not === ArrayHelper::isIn($value, $rule->range, $rule->strict)) {
33 18
            $result->addError($rule->message);
34
        }
35
36 30
        return $result;
37
    }
38
}
39