Passed
Pull Request — master (#288)
by Alexander
04:57 queued 02:09
created

InRangeHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 12
c 1
b 0
f 0
dl 0
loc 25
ccs 12
cts 12
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 16 3
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\RuleHandlerInterface;
13
use Yiisoft\Validator\ValidationContext;
14
15
/**
16
 * Validates that the value is among a list of values.
17
 *
18
 * The range can be specified via constructor.
19
 * If the {@see InRange::$not} is called, the rule will ensure the value is NOT among the specified range.
20
 */
21
final class InRangeHandler implements RuleHandlerInterface
22
{
23
    private FormatterInterface $formatter;
24
25 33
    public function __construct(?FormatterInterface $formatter = null)
26
    {
27 33
        $this->formatter = $formatter ?? new Formatter();
28
    }
29
30 32
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
31
    {
32 32
        if (!$rule instanceof InRange) {
33 1
            throw new UnexpectedRuleException(InRange::class, $rule);
34
        }
35
36 31
        $result = new Result();
37 31
        if ($rule->isNot() === ArrayHelper::isIn($value, $rule->getRange(), $rule->isStrict())) {
38 19
            $formattedMessage = $this->formatter->format(
39 19
                $rule->getMessage(),
40 19
                ['attribute' => $context->getAttribute(), 'value' => $value]
41
            );
42 19
            $result->addError($formattedMessage);
43
        }
44
45 31
        return $result;
46
    }
47
}
48