Passed
Pull Request — master (#222)
by Rustam
02:28
created

InRangeHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
wmc 6
eloc 14
dl 0
loc 30
ccs 13
cts 14
cp 0.9286
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 21 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\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Formatter;
10
use Yiisoft\Validator\FormatterInterface;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\ValidationContext;
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 InRangeHandler implements RuleHandlerInterface
21
{
22
    private FormatterInterface $formatter;
23
24 31
    public function __construct(?FormatterInterface $formatter = null)
25
    {
26 31
        $this->formatter = $formatter ?? new Formatter();
27
    }
28
29 31
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
30
    {
31 31
        if (!$rule instanceof InRange) {
32 1
            throw new UnexpectedRuleException(InRange::class, $rule);
33
        }
34
35 30
        $result = new Result();
36
37 30
        if ($value === null && $rule->isSkipOnEmpty()) {
38
            return $result;
39
        }
40
41 30
        if ($rule->isNot() === ArrayHelper::isIn($value, $rule->getRange(), $rule->isStrict())) {
42 18
            $formattedMessage = $this->formatter->format(
43 18
                $rule->getMessage(),
44 18
                ['attribute' => $context?->getAttribute(), 'value' => $value]
45
            );
46 18
            $result->addError($formattedMessage);
47
        }
48
49 30
        return $result;
50
    }
51
}
52