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

InRangeHandler::validate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0144

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 21
ccs 11
cts 12
cp 0.9167
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 3
crap 5.0144
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