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 greater than another value or attribute. |
15
|
|
|
* |
16
|
|
|
* The value being validated with {@see GreaterThan::$targetValue} or {@see GreaterThan::$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 GreaterThan::$type} to |
21
|
|
|
* {@see GreaterThan::TYPE_NUMBER} to enable numeric validation. |
22
|
|
|
*/ |
23
|
|
|
final class GreaterThanHandler implements RuleHandlerInterface |
24
|
|
|
{ |
25
|
|
|
private FormatterInterface $formatter; |
26
|
|
|
|
27
|
7 |
|
public function __construct(?FormatterInterface $formatter = null) |
28
|
|
|
{ |
29
|
7 |
|
$this->formatter = $formatter ?? new Formatter(); |
30
|
|
|
} |
31
|
|
|
|
32
|
7 |
|
public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result |
33
|
|
|
{ |
34
|
7 |
|
if (!$rule instanceof GreaterThan) { |
35
|
1 |
|
throw new UnexpectedRuleException(GreaterThan::class, $rule); |
36
|
|
|
} |
37
|
|
|
|
38
|
6 |
|
$result = new Result(); |
39
|
6 |
|
$targetValue = $rule->getTargetValue() ?? $context?->getDataSet()?->getAttributeValue($rule->getTargetAttribute()); |
|
|
|
|
40
|
|
|
|
41
|
6 |
|
if (!$this->isGreaterThan($value, $targetValue, $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
|
6 |
|
return $result; |
56
|
|
|
} |
57
|
|
|
|
58
|
6 |
|
private function isGreaterThan(mixed $value, mixed $targetValue, string $type): bool |
59
|
|
|
{ |
60
|
6 |
|
if ($type === GreaterThan::TYPE_NUMBER) { |
61
|
|
|
$value = (float)$value; |
62
|
|
|
$targetValue = (float)$targetValue; |
63
|
|
|
} else { |
64
|
6 |
|
$value = (string)$value; |
65
|
6 |
|
$targetValue = (string)$targetValue; |
66
|
|
|
} |
67
|
|
|
|
68
|
6 |
|
return $value > $targetValue; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|