1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule\Number; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Strings\NumericHelper; |
8
|
|
|
use Yiisoft\Validator\Result; |
9
|
|
|
use Yiisoft\Validator\Rule\RuleHandlerInterface; |
10
|
|
|
use Yiisoft\Validator\ValidationContext; |
11
|
|
|
use Yiisoft\Validator\ValidatorInterface; |
12
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Validates that the value is a number. |
16
|
|
|
* |
17
|
|
|
* The format of the number must match the regular expression specified in {@see Number::$integerPattern} |
18
|
|
|
* or {@see Number::$numberPattern}. Optionally, you may configure the {@see Number::min()} and {@see Number::max()} |
19
|
|
|
* to ensure the number is within certain range. |
20
|
|
|
*/ |
21
|
|
|
final class NumberHandler implements RuleHandlerInterface |
22
|
|
|
{ |
23
|
73 |
|
public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result |
24
|
|
|
{ |
25
|
73 |
|
if (!$rule instanceof Number) { |
26
|
1 |
|
throw new UnexpectedRuleException(Number::class, $rule); |
27
|
|
|
} |
28
|
|
|
|
29
|
72 |
|
$result = new Result(); |
30
|
|
|
|
31
|
72 |
|
if (is_bool($value) || !is_scalar($value)) { |
32
|
5 |
|
$message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.'; |
33
|
5 |
|
$result->addError($message, ['value' => $value]); |
34
|
5 |
|
return $result; |
35
|
|
|
} |
36
|
|
|
|
37
|
67 |
|
$pattern = $rule->asInteger ? $rule->integerPattern : $rule->numberPattern; |
38
|
|
|
|
39
|
67 |
|
if (!preg_match($pattern, NumericHelper::normalize($value))) { |
40
|
21 |
|
$message = $rule->asInteger ? 'Value must be an integer.' : 'Value must be a number.'; |
41
|
21 |
|
$result->addError($message, ['value' => $value]); |
42
|
46 |
|
} elseif ($rule->min !== null && $value < $rule->min) { |
43
|
11 |
|
$result->addError($rule->tooSmallMessage, ['min' => $rule->min]); |
44
|
38 |
|
} elseif ($rule->max !== null && $value > $rule->max) { |
45
|
5 |
|
$result->addError($rule->tooBigMessage, ['max' => $rule->max]); |
46
|
|
|
} |
47
|
|
|
|
48
|
67 |
|
return $result; |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|