Passed
Pull Request — master (#364)
by
unknown
02:54
created

CompareHandler::compareValues()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 18
ccs 15
cts 15
cp 1
rs 9.7666
cc 2
nc 2
nop 4
crap 2
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 73
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
28
    {
29 73
        if (!$rule instanceof Compare) {
30 1
            throw new UnexpectedRuleException(Compare::class, $rule);
31
        }
32
33 72
        $result = new Result();
34 72
        $targetAttribute = $rule->getTargetAttribute();
35 72
        $targetValue = $rule->getTargetValue();
36
37 72
        if ($targetValue === null && $targetAttribute !== null) {
38
            /** @var mixed $targetValue */
39 5
            $targetValue = $context->getDataSet()?->getAttributeValue($targetAttribute);
40 5
            if (!is_scalar($targetValue)) {
41 1
                return $result->addError($rule->getIncorrectDataSetTypeMessage(), [
42 1
                    'attribute' => $context->getAttribute(),
43 1
                    'type' => get_debug_type($targetValue),
44
                ]);
45
            }
46
        }
47
48 71
        if (!$this->compareValues($rule->getOperator(), $rule->getType(), $value, $targetValue)) {
49 39
            $parameters = [
50 39
                'attribute' => $context->getAttribute(),
51 39
                'targetValue' => $rule->getTargetValue(),
52 39
                'targetAttribute' => $rule->getTargetAttribute(),
53
                'targetValueOrAttribute' => $targetValue ?? $targetAttribute,
54
            ];
55 39
            is_scalar($value) ? $parameters['value'] = $value : $parameters['valueType'] = get_debug_type($value);
56
57 39
            $result->addError($rule->getMessage(), $parameters);
58
        }
59
60 71
        return $result;
61
    }
62
63
    /**
64
     * Compares two values with the specified operator.
65
     *
66
     * @param string $operator The comparison operator.
67
     * @param string $type The type of the values being compared.
68
     * @param mixed $value The value being compared.
69
     * @param mixed $targetValue Another value being compared.
70
     *
71
     * @return bool Whether the comparison using the specified operator is true.
72
     */
73 71
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
74
    {
75 71
        if ($type === Compare::TYPE_NUMBER) {
76 2
            $value = (float)$value;
77 2
            $targetValue = (float)$targetValue;
78
        } else {
79 69
            $value = (string)$value;
80 69
            $targetValue = (string)$targetValue;
81
        }
82 71
        return match ($operator) {
83 14
            '==' => $value == $targetValue,
84 8
            '===' => $value === $targetValue,
85 8
            '!=' => $value != $targetValue,
86 6
            '!==' => $value !== $targetValue,
87 8
            '>' => $value > $targetValue,
88 8
            '>=' => $value >= $targetValue,
89 8
            '<' => $value < $targetValue,
90 71
            '<=' => $value <= $targetValue,
91
        };
92
    }
93
}
94