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\ValidatorInterface; |
11
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
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
|
73 |
|
public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result |
23
|
|
|
{ |
24
|
73 |
|
if (!$rule instanceof Number) { |
25
|
1 |
|
throw new UnexpectedRuleException(Number::class, $rule); |
26
|
|
|
} |
27
|
|
|
|
28
|
72 |
|
$result = new Result(); |
29
|
|
|
|
30
|
72 |
|
if (is_bool($value) || !is_scalar($value)) { |
31
|
5 |
|
$message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.'; |
32
|
5 |
|
$result->addError($message, ['value' => $value]); |
33
|
5 |
|
return $result; |
34
|
|
|
} |
35
|
|
|
|
36
|
67 |
|
$pattern = $rule->asInteger ? $rule->integerPattern : $rule->numberPattern; |
37
|
|
|
|
38
|
67 |
|
if (!preg_match($pattern, NumericHelper::normalize($value))) { |
39
|
21 |
|
$message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.'; |
40
|
21 |
|
$result->addError($message, ['value' => $value]); |
41
|
46 |
|
} elseif ($rule->min !== null && $value < $rule->min) { |
42
|
11 |
|
$result->addError($rule->tooSmallMessage, ['min' => $rule->min]); |
43
|
38 |
|
} elseif ($rule->max !== null && $value > $rule->max) { |
44
|
5 |
|
$result->addError($rule->tooBigMessage, ['max' => $rule->max]); |
45
|
|
|
} |
46
|
|
|
|
47
|
67 |
|
return $result; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|