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

NumberHandler::validate()   C

Complexity

Conditions 12
Paths 13

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 26
ccs 17
cts 17
cp 1
rs 6.9666
cc 12
nc 13
nop 3
crap 12

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;
6
7
use Yiisoft\Strings\NumericHelper;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\ValidationContext;
10
use Yiisoft\Validator\ValidatorInterface;
11
use Yiisoft\Validator\Exception\UnexpectedRuleException;
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 NumberHandler implements RuleHandlerInterface
21
{
22 73
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
23
    {
24 73
        if (!$rule instanceof Number) {
25 1
            throw new UnexpectedRuleException(Number::class, $rule);
26
        }
27
28 72
        $result = new Result();
29
30 72
        if (is_bool($value) || !is_scalar($value)) {
31 5
            $message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.';
32 5
            $result->addError($message, ['value' => $value]);
33 5
            return $result;
34
        }
35
36 67
        $pattern = $rule->asInteger ? $rule->integerPattern : $rule->numberPattern;
37
38 67
        if (!preg_match($pattern, NumericHelper::normalize($value))) {
39 21
            $message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.';
40 21
            $result->addError($message, ['value' => $value]);
41 46
        } elseif ($rule->min !== null && $value < $rule->min) {
42 11
            $result->addError($rule->tooSmallMessage, ['min' => $rule->min]);
43 38
        } elseif ($rule->max !== null && $value > $rule->max) {
44 5
            $result->addError($rule->tooBigMessage, ['max' => $rule->max]);
45
        }
46
47 67
        return $result;
48
    }
49
}
50