|
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\RuleHandlerInterface; |
|
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
|
12
|
|
|
|
|
13
|
|
|
use function is_bool; |
|
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 NumberHandler implements RuleHandlerInterface |
|
23
|
|
|
{ |
|
24
|
114 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
|
25
|
|
|
{ |
|
26
|
114 |
|
if (!$rule instanceof Number) { |
|
27
|
1 |
|
throw new UnexpectedRuleException(Number::class, $rule); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
113 |
|
$result = new Result(); |
|
31
|
|
|
|
|
32
|
113 |
|
if (is_bool($value) || !is_scalar($value)) { |
|
33
|
14 |
|
$result->addError($rule->getNotANumberMessage(), [ |
|
34
|
14 |
|
'attribute' => $context->getAttribute(), |
|
35
|
|
|
'value' => $value, |
|
36
|
|
|
]); |
|
37
|
|
|
|
|
38
|
14 |
|
return $result; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
99 |
|
$pattern = $rule->isAsInteger() ? $rule->getIntegerPattern() : $rule->getNumberPattern(); |
|
42
|
|
|
|
|
43
|
99 |
|
if (!preg_match($pattern, NumericHelper::normalize($value))) { |
|
44
|
23 |
|
$result->addError( |
|
45
|
23 |
|
$rule->getNotANumberMessage(), |
|
46
|
|
|
[ |
|
47
|
23 |
|
'attribute' => $context->getAttribute(), |
|
48
|
|
|
'value' => $value, |
|
49
|
|
|
], |
|
50
|
|
|
); |
|
51
|
76 |
|
} elseif ($rule->getMin() !== null && $value < $rule->getMin()) { |
|
52
|
35 |
|
$result->addError( |
|
53
|
35 |
|
$rule->getTooSmallMessage(), |
|
54
|
|
|
[ |
|
55
|
35 |
|
'min' => $rule->getMin(), |
|
56
|
35 |
|
'attribute' => $context->getAttribute(), |
|
57
|
|
|
'value' => $value, |
|
58
|
|
|
], |
|
59
|
|
|
); |
|
60
|
53 |
|
} elseif ($rule->getMax() !== null && $value > $rule->getMax()) { |
|
61
|
17 |
|
$result->addError( |
|
62
|
17 |
|
$rule->getTooBigMessage(), |
|
63
|
|
|
[ |
|
64
|
17 |
|
'max' => $rule->getMax(), |
|
65
|
17 |
|
'attribute' => $context->getAttribute(), |
|
66
|
|
|
'value' => $value, |
|
67
|
|
|
], |
|
68
|
|
|
); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
99 |
|
return $result; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|