NumberHandler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 39
rs 10
ccs 21
cts 21
cp 1
wmc 9

1 Method

Rating   Name   Duplication   Size   Complexity  
B validate() 0 37 9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Strings\NumericHelper;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
13
use function is_bool;
14
15
/**
16
 * Validates that the value is a number.
17
 *
18
 * @see Number
19
 */
20
final class NumberHandler implements RuleHandlerInterface
21
{
22
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
23
    {
24 121
        if (!$rule instanceof AbstractNumber) {
25
            throw new UnexpectedRuleException(AbstractNumber::class, $rule);
26 121
        }
27 1
28
        $result = new Result();
29
30 120
        if (is_bool($value) || !is_scalar($value)) {
31
            $result->addError($rule->getIncorrectInputMessage(), [
32 120
                'attribute' => $context->getTranslatedAttribute(),
33 14
                'type' => get_debug_type($value),
34 14
            ]);
35 14
36
            return $result;
37
        }
38 14
39
        if (!preg_match($rule->getPattern(), NumericHelper::normalize($value))) {
40
            $result->addError($rule->getNotNumberMessage(), [
41 106
                'attribute' => $context->getTranslatedAttribute(),
42
                'value' => $value,
43 106
            ]);
44 23
        } elseif ($rule->getMin() !== null && $value < $rule->getMin()) {
45 23
            $result->addError($rule->getLessThanMinMessage(), [
46
                'min' => $rule->getMin(),
47
                'attribute' => $context->getTranslatedAttribute(),
48 83
                'value' => $value,
49 39
            ]);
50 39
        } elseif ($rule->getMax() !== null && $value > $rule->getMax()) {
51 39
            $result->addError($rule->getGreaterThanMaxMessage(), [
52
                'max' => $rule->getMax(),
53
                'attribute' => $context->getTranslatedAttribute(),
54 57
                'value' => $value,
55 20
            ]);
56 20
        }
57 20
58
        return $result;
59
    }
60
}
61