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
|
|
|
|