1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule\Trait; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Yiisoft\Validator\LimitInterface; |
9
|
|
|
use Yiisoft\Validator\Result; |
10
|
|
|
use Yiisoft\Validator\RuleInterface; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* A trait attachable to a handler of rule with limits. |
15
|
|
|
*/ |
16
|
|
|
trait LimitHandlerTrait |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* Runs limits specific validation. |
20
|
|
|
* |
21
|
|
|
* @param LimitInterface|RuleInterface $rule A rule matching to this handler. |
22
|
|
|
* @param ValidationContext $context Validation context. |
23
|
|
|
* @param int $number A validated number to compare with set limits. |
24
|
|
|
* @param Result $result Result for adding errors. |
25
|
|
|
* |
26
|
|
|
* @see LimitTrait for information about limits and messages. |
27
|
|
|
*/ |
28
|
85 |
|
private function validateLimits( |
29
|
|
|
LimitInterface|RuleInterface $rule, |
30
|
|
|
ValidationContext $context, |
31
|
|
|
int $number, |
32
|
|
|
Result $result |
33
|
|
|
): void { |
34
|
85 |
|
if (!$rule instanceof LimitInterface || !$rule instanceof RuleInterface) { |
35
|
2 |
|
throw new InvalidArgumentException('$rule must implement both LimitInterface and RuleInterface.'); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @var LimitTrait|RuleInterface $rule |
40
|
|
|
* @psalm-ignore-var |
41
|
|
|
*/ |
42
|
83 |
|
if ($rule->getExactly() !== null && $number !== $rule->getExactly()) { |
|
|
|
|
43
|
3 |
|
$result->addError($rule->getNotExactlyMessage(), [ |
|
|
|
|
44
|
3 |
|
'exactly' => $rule->getExactly(), |
45
|
3 |
|
'attribute' => $context->getAttribute(), |
46
|
|
|
]); |
47
|
|
|
|
48
|
3 |
|
return; |
49
|
|
|
} |
50
|
|
|
|
51
|
80 |
|
if ($rule->getMin() !== null && $number < $rule->getMin()) { |
|
|
|
|
52
|
42 |
|
$result->addError($rule->getLessThanMinMessage(), [ |
|
|
|
|
53
|
42 |
|
'min' => $rule->getMin(), |
54
|
42 |
|
'attribute' => $context->getAttribute(), |
55
|
|
|
]); |
56
|
|
|
} |
57
|
|
|
|
58
|
80 |
|
if ($rule->getMax() !== null && $number > $rule->getMax()) { |
|
|
|
|
59
|
5 |
|
$result->addError($rule->getGreaterThanMaxMessage(), [ |
|
|
|
|
60
|
5 |
|
'max' => $rule->getMax(), |
61
|
5 |
|
'attribute' => $context->getAttribute(), |
62
|
|
|
]); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|