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