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
|
|
|
/** |
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
|
112 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
23
|
|
|
{ |
24
|
112 |
|
if (!$rule instanceof Number) { |
25
|
1 |
|
throw new UnexpectedRuleException(Number::class, $rule); |
26
|
|
|
} |
27
|
|
|
|
28
|
111 |
|
$result = new Result(); |
29
|
|
|
|
30
|
111 |
|
if (is_bool($value) || !is_scalar($value)) { |
31
|
12 |
|
$result->addError( |
32
|
12 |
|
message: $rule->isAsInteger() ? 'Value must be an integer.' : 'Value must be a number.', |
33
|
12 |
|
parameters: ['value' => $value] |
34
|
|
|
); |
35
|
12 |
|
return $result; |
36
|
|
|
} |
37
|
|
|
|
38
|
99 |
|
$pattern = $rule->isAsInteger() ? $rule->getIntegerPattern() : $rule->getNumberPattern(); |
39
|
|
|
|
40
|
99 |
|
if (!preg_match($pattern, NumericHelper::normalize($value))) { |
41
|
23 |
|
$result->addError( |
42
|
23 |
|
message: $rule->isAsInteger() ? 'Value must be an integer.' : 'Value must be a number.', |
43
|
23 |
|
parameters: ['value' => $value] |
44
|
|
|
); |
45
|
76 |
|
} elseif ($rule->getMin() !== null && $value < $rule->getMin()) { |
46
|
34 |
|
$result->addError( |
47
|
34 |
|
message: $rule->getTooSmallMessage(), |
48
|
34 |
|
parameters: ['min' => $rule->getMin(), 'value' => $value] |
49
|
|
|
); |
50
|
54 |
|
} elseif ($rule->getMax() !== null && $value > $rule->getMax()) { |
51
|
18 |
|
$result->addError( |
52
|
18 |
|
message: $rule->getTooBigMessage(), |
53
|
18 |
|
parameters: ['max' => $rule->getMax(), 'value' => $value] |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
|
57
|
99 |
|
return $result; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|