Passed
Pull Request — master (#422)
by Alexander
03:36 queued 01:01
created

NumberHandler::validate()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 37
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 17
c 2
b 0
f 0
nc 6
nop 3
dl 0
loc 37
ccs 20
cts 20
cp 1
crap 6
rs 9.0777
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\Rule\Trait\LimitHandlerTrait;
11
use Yiisoft\Validator\RuleHandlerInterface;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function is_bool;
15
16
/**
17
 * Validates that the value is a number.
18
 *
19
 * The format of the number must match the regular expression specified in {@see Number::$integerPattern}
20
 * or {@see Number::$numberPattern}. Optionally, you may configure the {@see Number::min()} and {@see Number::max()}
21
 * to ensure the number is within certain range.
22
 */
23
final class NumberHandler implements RuleHandlerInterface
24 121
{
25
    use LimitHandlerTrait;
26 121
27 1
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
28
    {
29
        if (!$rule instanceof Number) {
30 120
            throw new UnexpectedRuleException(Number::class, $rule);
31
        }
32 120
33 14
        $result = new Result();
34 14
35 14
        if (is_bool($value) || !is_scalar($value)) {
36
            $result->addError($rule->getIncorrectInputMessage(), [
37
                'attribute' => $context->getAttribute(),
38 14
                'type' => get_debug_type($value),
39
            ]);
40
41 106
            return $result;
42
        }
43 106
44 23
        $pattern = $rule->isAsInteger() ? $rule->getIntegerPattern() : $rule->getNumberPattern();
45 23
        $value = NumericHelper::normalize($value);
46
47
        if (!preg_match($pattern, $value)) {
48 83
            return $result->addError($rule->getNotNumberMessage(), [
49 39
                'attribute' => $context->getAttribute(),
50 39
                'value' => $value,
51 39
            ]);
52
        }
53
54 57
        /**
55 20
         * @psalm-suppress InvalidOperand A value is guaranteed to be numeric here because of normalization via
56 20
         * `NumericHelper`and validation using regular expression  performed above.
57 20
         * @infection-ignore-all
58
         */
59
        $value = $value + 0;
60
61
        $this->validateLimits($rule, $context, $value, $result);
62 106
63
        return $result;
64
    }
65
}
66