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

CompareHandler::compareValues()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 4
eloc 16
c 4
b 0
f 0
nc 4
nop 4
dl 0
loc 21
ccs 0
cts 0
cp 0
crap 20
rs 9.7333
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->getTargetValue()),
66
            'targetAttribute' => $targetAttribute,
67
            'targetAttributeValue' => $targetAttribute !== null ? $this->getFormattedValue($targetValue) : null,
68
            'targetValueOrAttribute' => $targetAttribute ?? $this->getFormattedValue($targetValue),
69
            'value' => $this->getFormattedValue($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 ||
99
            is_scalar($value) ||
100
            $value instanceof Stringable ||
101
            $value instanceof DateTimeInterface;
102
    }
103
104
    /**
105
     * Gets representation of the value for using with error parameter.
106
     *
107
     * @param mixed $value The validated value.
108
     *
109
     * @return scalar|null Formatted value.
110
     */
111
    private function getFormattedValue(mixed $value): int|float|string|bool|null
112
    {
113
        if ($value === null || is_scalar($value)) {
114
            return $value;
115
        }
116
117
        if ($value instanceof Stringable) {
118
            return (string) $value;
119
        }
120
121
        if ($value instanceof DateTimeInterface) {
122
            return $value->format('U');
123
        }
124
125
        return get_debug_type($value);
126
    }
127
128
    /**
129
     * Compares two values according to the specified type and operator.
130
     *
131
     * @param string $operator The comparison operator. One of `==`, `===`, `!=`, `!==`, `>`, `>=`, `<`, `<=`.
132
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
133
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
134
     *
135
     * @param mixed $value The validated value.
136
     * @param mixed $targetValue "Target" value set in rule options.
137
     *
138
     * @return bool Whether the result of comparison using the specified operator is true.
139
     */
140
    private function compareValues(string $type, string $operator, mixed $value, mixed $targetValue): bool
141
    {
142
        if (!in_array($operator, ['==', '===', '!=', '!=='])) {
143
            if ($type === CompareType::STRING) {
144
                $value = (string) $value;
145
                $targetValue = (string) $targetValue;
146
            } elseif ($type === CompareType::NUMBER) {
147
                $value = $this->normalizeNumber($value);
148
                $targetValue = $this->normalizeNumber($targetValue);
149
            }
150
        }
151
152
        return match ($operator) {
153
            '==' => $this->checkValuesAreEqual($type, $value, $targetValue),
154
            '===' => $this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
155
            '!=' => !$this->checkValuesAreEqual($type, $value, $targetValue),
156
            '!==' => !$this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
157
            '>' => $value > $targetValue,
158
            '>=' => $value >= $targetValue,
159
            '<' => $value < $targetValue,
160
            '<=' => $value <= $targetValue,
161
        };
162
    }
163
164
    /**
165
     * Checks whether a validated value equals to "target" value. For types other than {@see CompareType::ORIGINAL},
166
     * handles strict comparison before type casting and takes edge cases for float numbers into account.
167
     *
168
     * @param string $type The type of the values being compared ({@see AbstractCompare::$type}).
169
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
170
     *
171
     * @param mixed $value The validated value.
172
     * @param mixed $targetValue "Target" value set in rule options.
173
     * @param bool $strict Whether the values must be equal (when set to `false`, default) / strictly equal (when set to
174
     * `true`).
175
     *
176
     * @return bool `true` if values are equal and `false` otherwise.
177
     */
178
    private function checkValuesAreEqual(string $type, mixed $value, mixed $targetValue, bool $strict = false): bool
179
    {
180
        if ($type === CompareType::ORIGINAL) {
181
            return $strict ? $value === $targetValue : $value == $targetValue;
182
        }
183
184
        if ($strict && gettype($value) !== gettype($targetValue)) {
185
            return false;
186
        }
187
188
        return match ($type) {
189
            CompareType::STRING => $this->normalizeString($value) === $this->normalizeString($targetValue),
190
            CompareType::NUMBER => $this->checkFloatsAreEqual(
191
                $this->normalizeNumber($value),
192
                $this->normalizeNumber($targetValue),
193
            ),
194
        };
195
    }
196
197
    /**
198
     * Checks whether a validated float number equals to "target" float number. Handles a known problem of losing
199
     * precision during arithmetical operations.
200
     *
201
     * @param float $value The validated number.
202
     * @param float $targetValue "Target" number set in rule options.
203
     *
204
     * @return bool `true` if numbers are equal and `false` otherwise.
205
     *
206
     * @link https://floating-point-gui.de/
207
     */
208
    private function checkFloatsAreEqual(float $value, float $targetValue): bool
209
    {
210
        return abs($value - $targetValue) < PHP_FLOAT_EPSILON;
211
    }
212
213
    /**
214
     * Normalizes number that might be stored in a different type to float number.
215
     *
216
     * @param mixed $number Raw number. Can be within an object implementing {@see Stringable} /
217
     * {@see DateTimeInterface} or other primitive type, such as `int`, `float`, `string`.
218
     *
219
     * @return float Float number ready for comparison.
220
     */
221
    private function normalizeNumber(mixed $number): float
222
    {
223
        if ($number instanceof Stringable) {
224
            $number = (string) $number;
225
        } elseif ($number instanceof DateTimeInterface) {
226
            $number = $number->format('U');
227
        }
228
229
        return (float) $number;
230
    }
231
232
    /**
233
     * Normalizes string that might be stored in a different type to simple string.
234
     *
235
     * @param mixed $string Raw string. Can be within an object implementing {@see DateTimeInterface} or other primitive
236
     * type, such as `int`, `float`, `string`.
237
     *
238
     * @return string String ready for comparison.
239
     */
240
    private function normalizeString(mixed $string): string
241
    {
242
        if ($string instanceof DateTimeInterface) {
243
            $string = $string->format('U');
244
        }
245
246
        return (string) $string;
247
    }
248
}
249