Passed
Pull Request — master (#320)
by Dmitriy
02:36
created

CompareHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
12
/**
13
 * Compares the specified value with another value.
14
 *
15
 * The value being compared with {@see Compare::$targetValue} or {@see Compare::$targetAttribute}, which is set
16
 * in the constructor.
17
 *
18
 * It supports different comparison operators, specified
19
 * via the {@see Compare::$operator}.
20
 *
21
 * The default comparison function is based on string values, which means the values
22
 * are compared byte by byte. When comparing numbers, make sure to change {@see Compare::$type} to
23
 * {@see Compare::TYPE_NUMBER} to enable numeric comparison.
24
 */
25
final class CompareHandler implements RuleHandlerInterface
26
{
27 75
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
28
    {
29 75
        if (!$rule instanceof Compare) {
30 7
            throw new UnexpectedRuleException(Compare::class, $rule);
31
        }
32
33 68
        $result = new Result();
34 68
        $targetAttribute = $rule->getTargetAttribute();
35 68
        $targetValue = $rule->getTargetValue();
36
37 68
        if ($targetValue === null && $targetAttribute !== null) {
38 4
            $targetValue = $context->getDataSet()?->getAttributeValue($targetAttribute);
39
        }
40
41 68
        if (!$this->compareValues($rule->getOperator(), $rule->getType(), $value, $targetValue)) {
42 38
            $result->addError(
43 38
                message: $rule->getMessage(),
44
                parameters: [
45 38
                    'targetValue' => $rule->getTargetValue(),
46 38
                    'targetAttribute' => $rule->getTargetAttribute(),
47 38
                    'targetValueOrAttribute' => $targetValue ?? $targetAttribute,
48
                    'value' => $value,
49
                ]
50
            );
51
        }
52
53 68
        return $result;
54
    }
55
56
    /**
57
     * Compares two values with the specified operator.
58
     *
59
     * @param string $operator The comparison operator.
60
     * @param string $type The type of the values being compared.
61
     * @param mixed $value The value being compared.
62
     * @param mixed $targetValue Another value being compared.
63
     *
64
     * @return bool Whether the comparison using the specified operator is true.
65
     */
66 68
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
67
    {
68 68
        if ($type === Compare::TYPE_NUMBER) {
69
            $value = (float)$value;
70
            $targetValue = (float)$targetValue;
71
        } else {
72 68
            $value = (string)$value;
73 68
            $targetValue = (string)$targetValue;
74
        }
75 68
        return match ($operator) {
76 13
            '==' => $value == $targetValue,
77 6
            '===' => $value === $targetValue,
78 8
            '!=' => $value != $targetValue,
79 6
            '!==' => $value !== $targetValue,
80 8
            '>' => $value > $targetValue,
81 8
            '>=' => $value >= $targetValue,
82 8
            '<' => $value < $targetValue,
83 11
            '<=' => $value <= $targetValue,
84 68
            default => false,
85
        };
86
    }
87
}
88