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

InRangeHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 32
    public function __construct(?FormatterInterface $formatter = null)
25
    {
26 32
        $this->formatter = $formatter ?? new Formatter();
27
    }
28
29 32
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
30
    {
31 32
        if (!$rule instanceof InRange) {
32 1
            throw new UnexpectedRuleException(InRange::class, $rule);
33
        }
34
35 31
        $result = new Result();
36
37 31
        if ($value === null && $rule->shouldSkipOnEmpty()) {
38
            return $result;
39
        }
40
41 31
        if ($rule->isNot() === ArrayHelper::isIn($value, $rule->getRange(), $rule->isStrict())) {
42 19
            $formattedMessage = $this->formatter->format(
43 19
                $rule->getMessage(),
44 19
                ['attribute' => $context?->getAttribute(), 'value' => $value]
45
            );
46 19
            $result->addError($formattedMessage);
47
        }
48
49 31
        return $result;
50
    }
51
}
52