|
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 |
|
*/ |
|
58
|
|
|
$value = $value + 0; |
|
59
|
|
|
|
|
60
|
|
|
$this->validateLimits($rule, $context, $value, $result); |
|
61
|
|
|
|
|
62
|
106 |
|
return $result; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|