Passed
Pull Request — master (#222)
by Alexander
04:47 queued 02:23
created

NumberValidator::validate()   B

Complexity

Conditions 11
Paths 12

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 14
c 1
b 0
f 0
nc 12
nop 4
dl 0
loc 22
ccs 15
cts 15
cp 1
crap 11
rs 7.3166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\RuleValidatorInterface;
10
use Yiisoft\Validator\ValidationContext;
11
use Yiisoft\Validator\ValidatorInterface;
12
13
/**
14
 * Validates that the value is a number.
15
 *
16
 * The format of the number must match the regular expression specified in {@see Number::$integerPattern}
17
 * or {@see Number::$numberPattern}. Optionally, you may configure the {@see Number::min()} and {@see Number::max()}
18
 * to ensure the number is within certain range.
19
 */
20
final class NumberValidator implements RuleValidatorInterface
21
{
22 72
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
23
    {
24 72
        $result = new Result();
25
26 72
        if (is_bool($value) || !is_scalar($value)) {
27 5
            $message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.';
28 5
            $result->addError($message, ['value' => $value]);
29 5
            return $result;
30
        }
31
32 67
        $pattern = $rule->asInteger ? $rule->integerPattern : $rule->numberPattern;
33
34 67
        if (!preg_match($pattern, NumericHelper::normalize($value))) {
35 21
            $message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.';
36 21
            $result->addError($message, ['value' => $value]);
37 46
        } elseif ($rule->min !== null && $value < $rule->min) {
38 11
            $result->addError($rule->tooSmallMessage, ['min' => $rule->min]);
39 38
        } elseif ($rule->max !== null && $value > $rule->max) {
40 5
            $result->addError($rule->tooBigMessage, ['max' => $rule->max]);
41
        }
42
43 67
        return $result;
44
    }
45
}
46