Passed
Pull Request — master (#521)
by
unknown
08:08 queued 05:40
created

CompareHandler::checkFloatsAreEqual()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
ccs 0
cts 0
cp 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use DateTimeInterface;
8
use Stringable;
9
use Yiisoft\Validator\Exception\UnexpectedRuleException;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\RuleHandlerInterface;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function gettype;
15
use function in_array;
16
17
/**
18
 * Compares the specified value with "target" value provided directly or within an attribute.
19
 *
20
 * @see AbstractCompare
21
 * @see Equal
22
 * @see GreaterThan
23
 * @see GreaterThanOrEqual
24
 * @see LessThan
25
 * @see LessThanOrEqual
26
 * @see Compare
27 84
 * @see NotEqual
28
 */
29 84
final class CompareHandler implements RuleHandlerInterface
30 1
{
31
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
32
    {
33 83
        if (!$rule instanceof AbstractCompare) {
34 83
            throw new UnexpectedRuleException(AbstractCompare::class, $rule);
35 4
        }
36 4
37 4
        $result = new Result();
38
        if (!$this->isInputCorrect($rule->getType(), $value)) {
39
            return $result->addError($rule->getIncorrectInputMessage(), [
40
                'attribute' => $context->getTranslatedAttribute(),
41 79
                'type' => get_debug_type($value),
42 79
            ]);
43
        }
44 79
45
        /** @var mixed $targetValue */
46 8
        $targetValue = $rule->getTargetValue();
47 8
        $targetAttribute = $rule->getTargetAttribute();
48 3
49 3
        if ($targetValue === null && $targetAttribute !== null) {
50
            /** @var mixed $targetValue */
51
            $targetValue = $context->getDataSet()->getAttributeValue($targetAttribute);
52
            if (!$this->isInputCorrect($rule->getType(), $targetValue)) {
53
                return $result->addError($rule->getIncorrectDataSetTypeMessage(), [
54 76
                    'type' => get_debug_type($targetValue),
55 34
                ]);
56
            }
57
        }
58 42
59 42
        if ($this->compareValues($rule->getType(), $rule->getOperator(), $value, $targetValue)) {
60 42
            return new Result();
61 42
        }
62
63
        return (new Result())->addError($rule->getMessage(), [
64
            'attribute' => $context->getTranslatedAttribute(),
65
            'targetValue' => $this->getFormattedValue($rule->getType(), $rule->getTargetValue()),
66
            'targetAttribute' => $targetAttribute,
67
            'targetAttributeValue' => $targetAttribute !== null ? $this->getFormattedValue($rule->getType(), $targetValue) : null,
68
            'targetValueOrAttribute' => $targetAttribute ?? $this->getFormattedValue($rule->getType(), $targetValue),
69
            'value' => $this->getFormattedValue($rule->getType(), $value),
70
        ]);
71
    }
72
73
    /**
74
     * Checks whether the validated value has correct type depending on selected {@see AbstractCompare::$type}.
75
     *
76
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
77 76
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
78
     *
79 76
     * @param mixed $value The validated value.
80 2
     *
81 2
     * @return bool `true` if value is correct and `false` otherwise.
82
     */
83 74
    private function isInputCorrect(string $type, mixed $value): bool
84 74
    {
85
        return $type !== CompareType::ORIGINAL ? $this->isValueAllowedForTypeCasting($value) : true;
86
    }
87 76
88 17
    /**
89 10
     * Checks whether the validated value is allowed for types that require type casting - {@see CompareType::NUMBER}
90 8
     * and {@see CompareType::STRING}.
91 6
     *
92 8
     * @param mixed $value The Validated value.
93 8
     *
94 8
     * @return bool `true` if value is allowed and `false` otherwise.
95 76
     */
96
    private function isValueAllowedForTypeCasting(mixed $value): bool
97
    {
98
        return $value === null || is_scalar(
99
            $value
100
        ) || $value instanceof Stringable || $value instanceof DateTimeInterface;
101
    }
102
103
    /**
104
     * Gets representation of the value for using with error parameter.
105
     *
106
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
107
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
108
     *
109
     * @param mixed $value The мalidated value.
110
     *
111
     * @return scalar|null Formatted value.
112
     */
113
    private function getFormattedValue(string $type, mixed $value): int|float|string|bool|null
114
    {
115
        if ($value === null || is_scalar($value)) {
116
            return $value;
117
        }
118
119
        if ($value instanceof Stringable && $type !== CompareType::ORIGINAL) {
120
            return (string) $value;
121
        }
122
123
        return get_debug_type($value);
124
    }
125
126
    /**
127
     * Compares two values according to the specified type and operator.
128
     *
129
     * @param string $operator The comparison operator. One of `==`, `===`, `!=`, `!==`, `>`, `>=`, `<`, `<=`.
130
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
131
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
132
     *
133
     * @param mixed $value The validated value.
134
     * @param mixed $targetValue "Target" value set in rule options.
135
     *
136
     * @return bool Whether the result of comparison using the specified operator is true.
137
     */
138
    private function compareValues(string $type, string $operator, mixed $value, mixed $targetValue): bool
139
    {
140
        if (!in_array($operator, ['==', '===', '!=', '!=='])) {
141
            if ($type === CompareType::STRING) {
142
                $value = (string) $value;
143
                $targetValue = (string) $targetValue;
144
            } elseif ($type === CompareType::NUMBER) {
145
                $value = $this->normalizeNumber($value);
146
                $targetValue = $this->normalizeNumber($targetValue);
147
            }
148
        }
149
150
        return match ($operator) {
151
            '==' => $this->checkValuesAreEqual($type, $value, $targetValue),
152
            '===' => $this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
153
            '!=' => !$this->checkValuesAreEqual($type, $value, $targetValue),
154
            '!==' => !$this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
155
            '>' => $value > $targetValue,
156
            '>=' => $value >= $targetValue,
157
            '<' => $value < $targetValue,
158
            '<=' => $value <= $targetValue,
159
        };
160
    }
161
162
    /**
163
     * Checks whether a validated value equals to "target" value. For types other than {@see CompareType::ORIGINAL},
164
     * handles strict comparison before type casting and takes edge cases for float numbers into account.
165
     *
166
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
167
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
168
     *
169
     * @param mixed $value The validated value.
170
     * @param mixed $targetValue "Target" value set in rule options.
171
     * @param bool $strict Whether the values must be equal (when set to `false`, default) / strictly equal (when set to
172
     * `true`).
173
     *
174
     * @return bool `true` if values are equal and `false` otherwise.
175
     */
176
    private function checkValuesAreEqual(string $type, mixed $value, mixed $targetValue, bool $strict = false): bool
177
    {
178
        if ($type === CompareType::ORIGINAL) {
179
            return $strict ? $value === $targetValue : $value == $targetValue;
180
        }
181
182
        if ($strict && gettype($value) !== gettype($targetValue)) {
183
            return false;
184
        }
185
186
        return match ($type) {
187
            CompareType::STRING => (string) $value === (string) $targetValue,
188
            CompareType::NUMBER => $this->checkFloatsAreEqual(
189
                $this->normalizeNumber($value),
190
                $this->normalizeNumber($targetValue),
191
            ),
192
        };
193
    }
194
195
    /**
196
     * Checks whether a validated float number equals to "target" float number. Handles a known problem of losing
197
     * precision during arithmetical operations.
198
     *
199
     * @param float $value The validated number.
200
     * @param float $targetValue "Target" number set in rule options.
201
     *
202
     * @return bool `true` if numbers are equal and `false` otherwise.
203
     *
204
     * @link https://floating-point-gui.de/
205
     */
206
    private function checkFloatsAreEqual(float $value, float $targetValue): bool
207
    {
208
        return abs($value - $targetValue) < PHP_FLOAT_EPSILON;
209
    }
210
211
    /**
212
     * Normalizes number that might be stored in a different type to float number.
213
     *
214
     * @param mixed $number Raw number. Can be within an object implementing {@see Stringable} interface or other
215
     * primitive type, such as `int`, `float`, `string`.
216
     *
217
     * @return float Float number ready for comparison.
218
     */
219
    private function normalizeNumber(mixed $number): float
220
    {
221
        if ($number instanceof Stringable) {
222
            $number = (string) $number;
223
        } elseif ($number instanceof DateTimeInterface) {
224
            $number = $number->format('U');
225
        }
226
227
        return (float) $number;
228
    }
229
}
230