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

CompareHandler   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 10
eloc 39
c 3
b 0
f 0
dl 0
loc 72
ccs 37
cts 37
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 0 38 8
A compareValues() 0 19 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 77
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
28
    {
29 77
        if (!$rule instanceof Compare) {
30 1
            throw new UnexpectedRuleException(Compare::class, $rule);
31
        }
32
33 76
        $result = new Result();
34 76
        if ($value !== null && !is_scalar($value)) {
35 1
            return $result->addError($rule->getIncorrectInputMessage(), [
36 1
                'attribute' => $context->getAttribute(),
37 1
                'type' => get_debug_type($value),
38
            ]);
39
        }
40
41 75
        $targetAttribute = $rule->getTargetAttribute();
42 75
        $targetValue = $rule->getTargetValue();
43
44 75
        if ($targetValue === null && $targetAttribute !== null) {
45
            /** @var mixed $targetValue */
46 5
            $targetValue = $context->getDataSet()?->getAttributeValue($targetAttribute);
47 5
            if (!is_scalar($targetValue)) {
48 1
                return $result->addError($rule->getIncorrectDataSetTypeMessage(), [
49 1
                    'attribute' => $context->getAttribute(),
50 1
                    'type' => get_debug_type($targetValue),
51
                ]);
52
            }
53
        }
54
55 74
        if ($this->compareValues($rule->getOperator(), $rule->getType(), $value, $targetValue)) {
56 34
            return $result;
57
        }
58
59 40
        return $result->addError($rule->getMessage(), [
60 40
            'attribute' => $context->getAttribute(),
61 40
            'targetValue' => $rule->getTargetValue(),
62 40
            'targetAttribute' => $rule->getTargetAttribute(),
63
            'targetValueOrAttribute' => $targetValue ?? $targetAttribute,
64
            'value' => $value,
65
        ]);
66
    }
67
68
    /**
69
     * Compares two values with the specified operator.
70
     *
71
     * @param string $operator The comparison operator.
72
     * @param string $type The type of the values being compared.
73
     * @param mixed $value The value being compared.
74
     * @param mixed $targetValue Another value being compared.
75
     *
76
     * @return bool Whether the comparison using the specified operator is true.
77
     */
78 74
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
79
    {
80 74
        if ($type === Compare::TYPE_NUMBER) {
81 2
            $value = (float) $value;
82 2
            $targetValue = (float) $targetValue;
83
        } else {
84 72
            $value = (string) $value;
85 72
            $targetValue = (string) $targetValue;
86
        }
87
88 74
        return match ($operator) {
89 16
            '==' => $value == $targetValue,
90 9
            '===' => $value === $targetValue,
91 8
            '!=' => $value != $targetValue,
92 6
            '!==' => $value !== $targetValue,
93 8
            '>' => $value > $targetValue,
94 8
            '>=' => $value >= $targetValue,
95 8
            '<' => $value < $targetValue,
96 74
            '<=' => $value <= $targetValue,
97
        };
98
    }
99
}
100