Passed
Pull Request — master (#521)
by Alexander
04:58 queued 02:24
created

CompareHandler   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 130
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 2 Features 0
Metric Value
eloc 57
c 7
b 2
f 0
dl 0
loc 130
rs 10
ccs 35
cts 35
cp 1
wmc 29

8 Methods

Rating   Name   Duplication   Size   Complexity  
B validate() 0 39 8
A isValueAllowedForTypeCasting() 0 3 3
A isInputCorrect() 0 3 2
A checkValuesAreEqual() 0 15 5
A prepareNumber() 0 7 2
A checkFloatsAreEqual() 0 3 1
A getFormattedValue() 0 7 4
A compareValues() 0 21 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Stringable;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\RuleHandlerInterface;
11
use Yiisoft\Validator\ValidationContext;
12
13
use function gettype;
14
use function in_array;
15
16
/**
17
 * Compares the specified value with "target" value provided directly or within an attribute.
18
 *
19
 * @see AbstractCompare
20
 * @see Equal
21
 * @see GreaterThan
22
 * @see GreaterThanOrEqual
23
 * @see LessThan
24
 * @see LessThanOrEqual
25
 * @see Compare
26
 * @see NotEqual
27 84
 */
28
final class CompareHandler implements RuleHandlerInterface
29 84
{
30 1
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
31
    {
32
        if (!$rule instanceof AbstractCompare) {
33 83
            throw new UnexpectedRuleException(AbstractCompare::class, $rule);
34 83
        }
35 4
36 4
        $result = new Result();
37 4
        if (!$this->isInputCorrect($rule, $value)) {
38
            return $result->addError($rule->getIncorrectInputMessage(), [
39
                'attribute' => $context->getTranslatedAttribute(),
40
                'type' => get_debug_type($value),
41 79
            ]);
42 79
        }
43
44 79
        /** @var mixed $targetValue */
45
        $targetValue = $rule->getTargetValue();
46 8
        $targetAttribute = $rule->getTargetAttribute();
47 8
48 3
        if ($targetValue === null && $targetAttribute !== null) {
49 3
            /** @var mixed $targetValue */
50
            $targetValue = $context->getDataSet()->getAttributeValue($targetAttribute);
51
            if (!$this->isInputCorrect($rule, $targetValue)) {
52
                return $result->addError($rule->getIncorrectDataSetTypeMessage(), [
53
                    'type' => get_debug_type($targetValue),
54 76
                ]);
55 34
            }
56
        }
57
58 42
        if ($this->compareValues($rule->getOperator(), $rule->getType(), $value, $targetValue)) {
59 42
            return new Result();
60 42
        }
61 42
62
        return (new Result())->addError($rule->getMessage(), [
63
            'attribute' => $context->getTranslatedAttribute(),
64
            'targetValue' => $this->getFormattedValue($rule->getTargetValue()),
65
            'targetAttribute' => $targetAttribute,
66
            'targetAttributeValue' => $targetAttribute !== null ? $this->getFormattedValue($targetValue) : null,
67
            'targetValueOrAttribute' => $targetAttribute ?? $this->getFormattedValue($targetValue),
68
            'value' => $this->getFormattedValue($value),
69
        ]);
70
    }
71
72
    private function isInputCorrect(AbstractCompare $rule, mixed $value): bool
73
    {
74
        return $rule->getType() !== CompareType::ORIGINAL ? $this->isValueAllowedForTypeCasting($value) : true;
75
    }
76
77 76
    private function isValueAllowedForTypeCasting(mixed $value): bool
78
    {
79 76
        return $value === null || is_scalar($value) || $value instanceof Stringable;
80 2
    }
81 2
82
    private function getFormattedValue(mixed $value): int|float|string|bool|null
83 74
    {
84 74
        if ($value === null || is_scalar($value)) {
85
            return $value;
86
        }
87 76
88 17
        return $value instanceof Stringable ? (string) $value : get_debug_type($value);
89 10
    }
90 8
91 6
    /**
92 8
     * Compares two values with the specified operator.
93 8
     *
94 8
     * @param string $operator The comparison operator. One of `==`, `===`, `!=`, `!==`, `>`, `>=`, `<`, `<=`.
95 76
     * @param string $type The type of the values being compared.
96
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
97
     *
98
     * @param mixed $value The validated value.
99
     * @param mixed $targetValue "Target" value set in rule options.
100
     *
101
     * @return bool Whether the result of comparison using the specified operator is true.
102
     */
103
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
104
    {
105
        if (!in_array($operator, ['==', '===', '!=', '!=='])) {
106
            if ($type === CompareType::STRING) {
107
                $value = (string) $value;
108
                $targetValue = (string) $targetValue;
109
            } elseif ($type === CompareType::NUMBER) {
110
                $value = $this->prepareNumber($value);
111
                $targetValue = $this->prepareNumber($targetValue);
112
            }
113
        }
114
115
        return match ($operator) {
116
            '==' => $this->checkValuesAreEqual($type, $value, $targetValue),
117
            '===' => $this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
118
            '!=' => !$this->checkValuesAreEqual($type, $value, $targetValue),
119
            '!==' => !$this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
120
            '>' => $value > $targetValue,
121
            '>=' => $value >= $targetValue,
122
            '<' => $value < $targetValue,
123
            '<=' => $value <= $targetValue,
124
        };
125
    }
126
127
    private function checkValuesAreEqual(string $type, mixed $value, mixed $targetValue, bool $strict = false): bool
128
    {
129
        if ($type === CompareType::ORIGINAL) {
130
            return $strict ? $value === $targetValue : $value == $targetValue;
131
        }
132
133
        if ($strict && gettype($value) !== gettype($targetValue)) {
134
            return false;
135
        }
136
137
        return match ($type) {
138
            CompareType::STRING => (string) $value === (string) $targetValue,
139
            CompareType::NUMBER => $this->checkFloatsAreEqual(
140
                $this->prepareNumber($value),
141
                $this->prepareNumber($targetValue),
142
            ),
143
        };
144
    }
145
146
    private function checkFloatsAreEqual(float $value, float $targetValue): bool
147
    {
148
        return abs($value - $targetValue) < PHP_FLOAT_EPSILON;
149
    }
150
151
    private function prepareNumber(mixed $number): float
152
    {
153
        if ($number instanceof Stringable) {
154
            $number = (string) $number;
155
        }
156
157
        return (float) $number;
158
    }
159
}
160