Passed
Pull Request — master (#222)
by Dmitriy
02:36
created

NumberValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
C validate() 0 26 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Number;
6
7
use Yiisoft\Strings\NumericHelper;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\AtLeast\AtLeast;
10
use Yiisoft\Validator\Rule\RuleValidatorInterface;
11
use Yiisoft\Validator\ValidationContext;
12
use Yiisoft\Validator\ValidatorInterface;
13
use Yiisoft\Validator\Exception\UnexpectedRuleException;
14
15
/**
16
 * Validates that the value is a number.
17
 *
18
 * The format of the number must match the regular expression specified in {@see Number::$integerPattern}
19
 * or {@see Number::$numberPattern}. Optionally, you may configure the {@see Number::min()} and {@see Number::max()}
20
 * to ensure the number is within certain range.
21
 */
22
final class NumberValidator implements RuleValidatorInterface
23
{
24 73
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
25
    {
26 73
        if (!$rule instanceof Number) {
27 1
            throw new UnexpectedRuleException(Number::class, $rule);
28
        }
29
30 72
        $result = new Result();
31
32 72
        if (is_bool($value) || !is_scalar($value)) {
33 5
            $message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.';
34 5
            $result->addError($message, ['value' => $value]);
35 5
            return $result;
36
        }
37
38 67
        $pattern = $rule->asInteger ? $rule->integerPattern : $rule->numberPattern;
39
40 67
        if (!preg_match($pattern, NumericHelper::normalize($value))) {
41 21
            $message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.';
42 21
            $result->addError($message, ['value' => $value]);
43 46
        } elseif ($rule->min !== null && $value < $rule->min) {
44 11
            $result->addError($rule->tooSmallMessage, ['min' => $rule->min]);
45 38
        } elseif ($rule->max !== null && $value > $rule->max) {
46 5
            $result->addError($rule->tooBigMessage, ['max' => $rule->max]);
47
        }
48
49 67
        return $result;
50
    }
51
}
52