Passed
Pull Request — master (#248)
by Rustam
12:42
created

CompareHandler   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 94.29%

Importance

Changes 0
Metric Value
wmc 8
eloc 36
c 0
b 0
f 0
dl 0
loc 69
ccs 33
cts 35
cp 0.9429
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 29 5
A __construct() 0 3 1
A compareValues() 0 19 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Formatter;
9
use Yiisoft\Validator\FormatterInterface;
10
use Yiisoft\Validator\Result;
11
use Yiisoft\Validator\ValidationContext;
12
13
/**
14
 * Compares the specified value with another value.
15
 *
16
 * The value being compared with {@see Compare::$targetValue} or {@see Compare::$targetAttribute}, which is set
17
 * in the constructor.
18
 *
19
 * It supports different comparison operators, specified
20
 * via the {@see Compare::$operator}.
21
 *
22
 * The default comparison function is based on string values, which means the values
23
 * are compared byte by byte. When comparing numbers, make sure to change {@see Compare::$type} to
24
 * {@see Compare::TYPE_NUMBER} to enable numeric comparison.
25
 */
26
final class CompareHandler implements RuleHandlerInterface
27
{
28
    private FormatterInterface $formatter;
29
30 35
    public function __construct(?FormatterInterface $formatter = null)
31
    {
32 35
        $this->formatter = $formatter ?? new Formatter();
33
    }
34
35 35
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
36
    {
37 35
        if (!$rule instanceof Compare) {
38 1
            throw new UnexpectedRuleException(Compare::class, $rule);
39
        }
40
41 34
        $result = new Result();
42 34
        $targetAttribute = $rule->getTargetAttribute();
43 34
        $targetValue = $rule->getTargetValue();
44
45 34
        if ($targetValue === null && $targetAttribute !== null) {
46 4
            $targetValue = $context?->getDataSet()?->getAttributeValue($targetAttribute);
47
        }
48
49 34
        if (!$this->compareValues($rule->getOperator(), $rule->getType(), $value, $targetValue)) {
50 17
            $formattedMessage = $this->formatter->format(
51 17
                $rule->getMessage(),
52
                [
53 17
                    'attribute' => $context?->getAttribute(),
54 17
                    'targetValue' => $rule->getTargetValue(),
55 17
                    'targetAttribute' => $rule->getTargetAttribute(),
56 17
                    'targetValueOrAttribute' => $targetValue ?? $targetAttribute,
57
                    'value' => $value,
58
                ]
59
            );
60 17
            $result->addError($formattedMessage);
61
        }
62
63 34
        return $result;
64
    }
65
66
    /**
67
     * Compares two values with the specified operator.
68
     *
69
     * @param string $operator the comparison operator
70
     * @param string $type the type of the values being compared
71
     * @param mixed $value the value being compared
72
     * @param mixed $targetValue another value being compared
73
     *
74
     * @return bool whether the comparison using the specified operator is true.
75
     */
76 34
    private function compareValues(string $operator, string $type, mixed $value, mixed $targetValue): bool
77
    {
78 34
        if ($type === Compare::TYPE_NUMBER) {
79
            $value = (float)$value;
80
            $targetValue = (float)$targetValue;
81
        } else {
82 34
            $value = (string)$value;
83 34
            $targetValue = (string)$targetValue;
84
        }
85 34
        return match ($operator) {
86 6
            '==' => $value == $targetValue,
87 5
            '===' => $value === $targetValue,
88 5
            '!=' => $value != $targetValue,
89 4
            '!==' => $value !== $targetValue,
90 3
            '>' => $value > $targetValue,
91 3
            '>=' => $value >= $targetValue,
92 3
            '<' => $value < $targetValue,
93 5
            '<=' => $value <= $targetValue,
94 34
            default => false,
95
        };
96
    }
97
}
98