Passed
Pull Request — master (#521)
by
unknown
02:36
created

CompareHandler::checkValuesAreEqual()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 5
eloc 9
c 2
b 1
f 0
nc 4
nop 4
dl 0
loc 15
ccs 0
cts 0
cp 0
crap 30
rs 9.6111
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
    /**
73
     * Checks whether the validated value has correct type depending on selected {@see AbstractCompare::$type}.
74
     * @param AbstractCompare $rule The rule used for comparison.
75
     * @param mixed $value The validated value.
76
     * @return bool `true` if value is correct and `false` otherwise.
77 76
     */
78
    private function isInputCorrect(AbstractCompare $rule, mixed $value): bool
79 76
    {
80 2
        return $rule->getType() !== CompareType::ORIGINAL ? $this->isValueAllowedForTypeCasting($value) : true;
81 2
    }
82
83 74
    /**
84 74
     * Checks whether the validated value is allowed for types that require type casting - {@see CompareType::NUMBER}
85
     * and {@see CompareType::STRING}.
86
     * @param mixed $value The Validated value.
87 76
     * @return bool `true` if value is allowed and `false` otherwise.
88 17
     */
89 10
    private function isValueAllowedForTypeCasting(mixed $value): bool
90 8
    {
91 6
        return $value === null || is_scalar($value) || $value instanceof Stringable;
92 8
    }
93 8
94 8
    /**
95 76
     * Gets representation of the value for using with error parameter.
96
     *
97
     * @param mixed $value The мalidated value.
98
     * @return scalar|null Formatted value.
99
     */
100
    private function getFormattedValue(mixed $value): int|float|string|bool|null
101
    {
102
        if ($value === null || is_scalar($value)) {
103
            return $value;
104
        }
105
106
        return $value instanceof Stringable ? (string) $value : get_debug_type($value);
107
    }
108
109
    /**
110
     * Compares two values according to the specified type and operator.
111
     *
112
     * @param string $operator The comparison operator. One of `==`, `===`, `!=`, `!==`, `>`, `>=`, `<`, `<=`.
113
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
114
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
115
     *
116
     * @param mixed $value The validated value.
117
     * @param mixed $targetValue "Target" value set in rule options.
118
     *
119
     * @return bool Whether the result of comparison using the specified operator is true.
120
     */
121
    private function compareValues(string $type, string $operator, mixed $value, mixed $targetValue): bool
122
    {
123
        if (!in_array($operator, ['==', '===', '!=', '!=='])) {
124
            if ($type === CompareType::STRING) {
125
                $value = (string) $value;
126
                $targetValue = (string) $targetValue;
127
            } elseif ($type === CompareType::NUMBER) {
128
                $value = $this->normalizeNumber($value);
129
                $targetValue = $this->normalizeNumber($targetValue);
130
            }
131
        }
132
133
        return match ($operator) {
134
            '==' => $this->checkValuesAreEqual($type, $value, $targetValue),
135
            '===' => $this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
136
            '!=' => !$this->checkValuesAreEqual($type, $value, $targetValue),
137
            '!==' => !$this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
138
            '>' => $value > $targetValue,
139
            '>=' => $value >= $targetValue,
140
            '<' => $value < $targetValue,
141
            '<=' => $value <= $targetValue,
142
        };
143
    }
144
145
    /**
146
     * Checks whether a validated value equals to "target" value. For types other than {@see CompareType::ORIGINAL},
147
     * handles strict comparison before type casting and takes edge cases for float numbers into account.
148
     *
149
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
150
     * @param mixed $value The validated value.
151
     * @param mixed $targetValue "Target" value set in rule options.
152
     * @param bool $strict Whether the values must be equal (when set to `false`, default) / strictly equal (when set to
153
     * `true`).
154
     * @return bool `true` if values are equal and `false` otherwise.
155
     */
156
    private function checkValuesAreEqual(string $type, mixed $value, mixed $targetValue, bool $strict = false): bool
157
    {
158
        if ($type === CompareType::ORIGINAL) {
159
            return $strict ? $value === $targetValue : $value == $targetValue;
160
        }
161
162
        if ($strict && gettype($value) !== gettype($targetValue)) {
163
            return false;
164
        }
165
166
        return match ($type) {
167
            CompareType::STRING => (string) $value === (string) $targetValue,
168
            CompareType::NUMBER => $this->checkFloatsAreEqual(
169
                $this->normalizeNumber($value),
170
                $this->normalizeNumber($targetValue),
171
            ),
172
        };
173
    }
174
175
    /**
176
     * Checks whether a validated float number equals to "target" float number. Handles a known problem of losing
177
     * precision during arithmetical operations.
178
     *
179
     * @param float $value The validated number.
180
     * @param float $targetValue "Target" number set in rule options.
181
     * @return bool `true` if numbers are equal and `false` otherwise.
182
     * @link https://floating-point-gui.de/
183
     */
184
    private function checkFloatsAreEqual(float $value, float $targetValue): bool
185
    {
186
        return abs($value - $targetValue) < PHP_FLOAT_EPSILON;
187
    }
188
189
    /**
190
     * Normalizes number that might be stored in a different type to float number.
191
     *
192
     * @param mixed $number Raw number. Can be within an object implementing {@see Stringable} interface or other
193
     * primitive type, such as `int`, `float`, `string`.
194
     * @return float Float number ready for comparison.
195
     */
196
    private function normalizeNumber(mixed $number): float
197
    {
198
        if ($number instanceof Stringable) {
199
            $number = (string) $number;
200
        }
201
202
        return (float) $number;
203
    }
204
}
205