Passed
Pull Request — master (#521)
by Alexander
05:27 queued 02:29
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 1
Bugs 1 Features 0
Metric Value
cc 5
dl 0
loc 15
rs 9.6111
c 1
b 1
f 0
eloc 9
nc 4
nop 4
ccs 0
cts 0
cp 0
crap 30
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 another value.
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
        $targetValue = $rule->getTargetValue();
45
        $targetAttribute = $rule->getTargetAttribute();
46 8
47 8
        if ($targetValue === null && $targetAttribute !== null) {
48 3
            /** @var mixed $targetValue */
49 3
            $targetValue = $context->getDataSet()->getAttributeValue($targetAttribute);
50
            if (!$this->isInputCorrect($rule, $targetValue)) {
51
                return $result->addError($rule->getIncorrectDataSetTypeMessage(), [
52
                    'type' => get_debug_type($targetValue),
53
                ]);
54 76
            }
55 34
        }
56
57
        if ($this->compareValues($rule->getOperator(), $rule->getType(), $value, $targetValue)) {
58 42
            return new Result();
59 42
        }
60 42
61 42
        return (new Result())->addError($rule->getMessage(), [
62
            'attribute' => $context->getTranslatedAttribute(),
63
            'targetValue' => $rule->getTargetValue(),
64
            'targetAttribute' => $targetAttribute,
65
            'targetAttributeValue' => $targetAttribute !== null ? $this->getFormattedValue($targetValue) : null,
66
            'targetValueOrAttribute' => $targetAttribute ?? $this->getFormattedValue($targetValue),
67
            'value' => $this->getFormattedValue($value),
68
        ]);
69
    }
70
71
    private function isInputCorrect(AbstractCompare $rule, mixed $value)
72
    {
73
        return $rule->getType() !== CompareType::ORIGINAL ? $this->isValueSimple($value) : true;
74
    }
75
76
    private function isValueSimple(mixed $value): bool
77 76
    {
78
        return $value === null || is_scalar($value) || $value instanceof Stringable;
79 76
    }
80 2
81 2
    private function getFormattedValue(mixed $value): int|float|string|Stringable|bool|null
82
    {
83 74
        return $this->isValueSimple($value) ? $value : get_debug_type($value);
84 74
    }
85
86
    /**
87 76
     * Compares two values with the specified operator.
88 17
     *
89 10
     * @param string $operator The comparison operator. One of `==`, `===`, `!=`, `!==`, `>`, `>=`, `<`, `<=`.
90 8
     * @param string $type The type of the values being compared.
91 6
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
92 8
     *
93 8
     * @param mixed $value The value being compared.
94 8
     * @param mixed $targetValue Another value being compared.
95 76
     *
96
     * @return bool Whether the result of comparison using the specified operator is true.
97
     */
98
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
99
    {
100
        if (!in_array($operator, ['==', '===', '!=', '!=='])) {
101
            if ($type === CompareType::STRING) {
102
                $value = (string) $value;
103
                $targetValue = (string) $targetValue;
104
            } elseif ($type === CompareType::NUMBER) {
105
                $value = $this->prepareNumber($value);
106
                $targetValue = $this->prepareNumber($targetValue);
107
            }
108
        }
109
110
        return match ($operator) {
111
            '==' => $this->checkValuesAreEqual($type, $value, $targetValue),
112
            '===' => $this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
113
            '!=' => !$this->checkValuesAreEqual($type, $value, $targetValue),
114
            '!==' => !$this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
115
            '>' => $value > $targetValue,
116
            '>=' => $value >= $targetValue,
117
            '<' => $value < $targetValue,
118
            '<=' => $value <= $targetValue,
119
        };
120
    }
121
122
    private function checkValuesAreEqual(string $type, mixed $value, mixed $targetValue, bool $strict = false): bool
123
    {
124
        if ($type === CompareType::ORIGINAL) {
125
            return $strict ? $value === $targetValue : $value == $targetValue;
126
        }
127
128
        if ($strict && gettype($value) !== gettype($targetValue)) {
129
            return false;
130
        }
131
132
        return match ($type) {
133
            CompareType::STRING => (string) $value === (string) $targetValue,
134
            CompareType::NUMBER => $this->checkFloatsAreEqual(
135
                $this->prepareNumber($value),
136
                $this->prepareNumber($targetValue),
137
            ),
138
        };
139
    }
140
141
    private function checkFloatsAreEqual(float $value, float $targetValue): bool
142
    {
143
        return abs($value - $targetValue) < PHP_FLOAT_EPSILON;
144
    }
145
146
    private function prepareNumber(int|float|string|Stringable|bool|null $number): float
147
    {
148
        if ($number instanceof Stringable) {
149
            $number = (string) $number;
150
        }
151
152
        return (float) $number;
153
    }
154
}
155