1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
8
|
|
|
use Yiisoft\Validator\Formatter; |
9
|
|
|
use Yiisoft\Validator\FormatterInterface; |
10
|
|
|
use Yiisoft\Validator\Result; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Validates if the specified value is less than or equal to another value or attribute. |
15
|
|
|
* |
16
|
|
|
* The value being validated with {@see LessThanOrEqual::$targetValue} or {@see LessThanOrEqual::$targetAttribute}, which |
17
|
|
|
* is set in the constructor. |
18
|
|
|
* |
19
|
|
|
* The default validation function is based on string values, which means the values |
20
|
|
|
* are compared byte by byte. When validating numbers, make sure to change {@see LessThanOrEqual::$type} to |
21
|
|
|
* {@see LessThanOrEqual::TYPE_NUMBER} to enable numeric validation. |
22
|
|
|
*/ |
23
|
|
|
final class LessThanOrEqualHandler implements RuleHandlerInterface |
24
|
|
|
{ |
25
|
|
|
private FormatterInterface $formatter; |
26
|
|
|
|
27
|
9 |
|
public function __construct(?FormatterInterface $formatter = null) |
28
|
|
|
{ |
29
|
9 |
|
$this->formatter = $formatter ?? new Formatter(); |
30
|
|
|
} |
31
|
|
|
|
32
|
9 |
|
public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result |
33
|
|
|
{ |
34
|
9 |
|
if (!$rule instanceof LessThanOrEqual) { |
35
|
1 |
|
throw new UnexpectedRuleException(LessThanOrEqual::class, $rule); |
36
|
|
|
} |
37
|
|
|
|
38
|
8 |
|
$result = new Result(); |
39
|
8 |
|
$expectedValue = $rule->getTargetValue() ?? $context?->getDataSet()?->getAttributeValue($rule->getTargetAttribute()); |
|
|
|
|
40
|
|
|
|
41
|
8 |
|
if (!$this->isLessThanOrEqual($value, $expectedValue, $rule->getType())) { |
42
|
4 |
|
$formattedMessage = $this->formatter->format( |
43
|
4 |
|
$rule->getMessage(), |
44
|
|
|
[ |
45
|
4 |
|
'attribute' => $context?->getAttribute(), |
46
|
4 |
|
'targetAttribute' => $rule->getTargetValue(), |
47
|
4 |
|
'targetValue' => $rule->getTargetValue(), |
48
|
4 |
|
'targetValueOrAttribute' => $rule->getTargetValue() ?? $rule->getTargetAttribute(), |
49
|
|
|
'value' => $value, |
50
|
|
|
] |
51
|
|
|
); |
52
|
4 |
|
$result->addError($formattedMessage); |
53
|
|
|
} |
54
|
|
|
|
55
|
8 |
|
return $result; |
56
|
|
|
} |
57
|
|
|
|
58
|
8 |
|
private function isLessThanOrEqual(mixed $value, mixed $expectedValue, string $type): bool |
59
|
|
|
{ |
60
|
8 |
|
if ($type === LessThanOrEqual::TYPE_NUMBER) { |
61
|
|
|
$value = (float)$value; |
62
|
|
|
$expectedValue = (float)$expectedValue; |
63
|
|
|
} else { |
64
|
8 |
|
$value = (string)$value; |
65
|
8 |
|
$expectedValue = (string)$expectedValue; |
66
|
|
|
} |
67
|
|
|
|
68
|
8 |
|
return $value <= $expectedValue; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|