Passed
Pull Request — master (#521)
by Alexander
11:59 queued 09:05
created

CompareHandler::isInputCorrect()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 3
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 7
rs 10
ccs 4
cts 4
cp 1
crap 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 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
        $targetAttribute = $rule->getTargetAttribute();
45
        $targetValue = $rule->getTargetValue();
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
        if ($rule->getType() === CompareType::ORIGINAL) {
62
            return (new Result())->addError($rule->getMessage(), [
63
                'attribute' => $context->getTranslatedAttribute(),
64
            ]);
65
        }
66
67
        return (new Result())->addError($rule->getMessage(), [
68
            'attribute' => $context->getTranslatedAttribute(),
69
            'targetValue' => $rule->getTargetValue(),
70
            'targetAttribute' => $rule->getTargetAttribute(),
71
            'targetValueOrAttribute' => $targetValue ?? $targetAttribute,
72
            'value' => $value,
73
        ]);
74
    }
75
76
    private function isInputCorrect(AbstractCompare $rule, mixed $value)
77 76
    {
78
        if ($rule->getType() !== CompareType::ORIGINAL) {
79 76
            return $value === null || is_scalar($value) || $value instanceof Stringable;
80 2
        }
81 2
82
        return true;
83 74
    }
84 74
85
    /**
86
     * Compares two values with the specified operator.
87 76
     *
88 17
     * @param string $operator The comparison operator. One of `==`, `===`, `!=`, `!==`, `>`, `>=`, `<`, `<=`.
89 10
     * @param string $type The type of the values being compared.
90 8
     * @psalm-param CompareType::ORIGINAL | CompareType::STRING | CompareType::NUMBER $type
91 6
     *
92 8
     * @param mixed $value The value being compared.
93 8
     * @param mixed $targetValue Another value being compared.
94 8
     *
95 76
     * @return bool Whether the result of comparison using the specified operator is true.
96
     */
97
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
98
    {
99
        if (!in_array($operator, ['==', '===', '!=', '!=='])) {
100
            if ($type === CompareType::STRING) {
101
                $value = (string) $value;
102
                $targetValue = (string) $targetValue;
103
            } elseif ($type === CompareType::NUMBER) {
104
                $value = (float) $value;
105
                $targetValue = (float) $targetValue;
106
            }
107
        }
108
109
        return match ($operator) {
110
            '==' => $this->checkValuesAreEqual($type, $value, $targetValue),
111
            '===' => $this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
112
            '!=' => !$this->checkValuesAreEqual($type, $value, $targetValue),
113
            '!==' => !$this->checkValuesAreEqual($type, $value, $targetValue, strict: true),
114
            '>' => $value > $targetValue,
115
            '>=' => $value >= $targetValue,
116
            '<' => $value < $targetValue,
117
            '<=' => $value <= $targetValue,
118
        };
119
    }
120
121
    private function checkValuesAreEqual(string $type, mixed $value, mixed $targetValue, bool $strict = false): bool
122
    {
123
        if ($strict && gettype($value) !== gettype($targetValue)) {
124
            return false;
125
        }
126
127
        return match ($type) {
128
            CompareType::ORIGINAL => $value === $targetValue,
129
            CompareType::STRING => (string) $value === (string) $targetValue,
130
            CompareType::NUMBER => $this->checkFloatsAreEqual((float) (string) $value, (float) (string) $targetValue),
131
        };
132
    }
133
134
    private function checkFloatsAreEqual(float $value, float $targetValue): bool
135
    {
136
        return abs($value - $targetValue) < PHP_FLOAT_EPSILON;
137
    }
138
}
139