Passed
Pull Request — master (#222)
by Rustam
02:32
created

CompareToHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 a constant {@see CompareTo::$compareValue}, which is set
17
 * in the constructor.
18
 *
19
 * It supports different comparison operators, specified
20
 * via the {@see CompareTo::$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 CompareTo::$type} to
24
 * {@see CompareTo::TYPE_NUMBER} to enable numeric comparison.
25
 */
26
final class CompareToHandler implements RuleHandlerInterface
27
{
28
    private FormatterInterface $formatter;
29
30 31
    public function __construct(?FormatterInterface $formatter = null)
31
    {
32 31
        $this->formatter = $formatter ?? new Formatter();
33
    }
34
35 31
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
36
    {
37 31
        if (!$rule instanceof CompareTo) {
38 1
            throw new UnexpectedRuleException(CompareTo::class, $rule);
39
        }
40
41 30
        $result = new Result();
42
43 30
        if (!$this->compareValues($rule->getOperator(), $rule->getType(), $value, $rule->getCompareValue())) {
44 15
            $formattedMessage = $this->formatter->format(
45 15
                $rule->getMessage(),
46
                [
47 15
                    'attribute' => $context?->getAttribute(),
48 15
                    'compareValue' => $rule->getCompareValue(),
49
                    'value' => $value,
50
                ]
51
            );
52 15
            $result->addError($formattedMessage);
53
        }
54
55 30
        return $result;
56
    }
57
58
    /**
59
     * Compares two values with the specified operator.
60
     *
61
     * @param string $operator the comparison operator
62
     * @param string $type the type of the values being compared
63
     * @param mixed $value the value being compared
64
     * @param mixed $compareValue another value being compared
65
     *
66
     * @return bool whether the comparison using the specified operator is true.
67
     */
68 30
    private function compareValues(string $operator, string $type, mixed $value, mixed $compareValue): bool
69
    {
70 30
        if ($type === CompareTo::TYPE_NUMBER) {
71
            $value = (float)$value;
72
            $compareValue = (float)$compareValue;
73
        } else {
74 30
            $value = (string)$value;
75 30
            $compareValue = (string)$compareValue;
76
        }
77 30
        return match ($operator) {
78 5
            '==' => $value == $compareValue,
79 4
            '===' => $value === $compareValue,
80 5
            '!=' => $value != $compareValue,
81 4
            '!==' => $value !== $compareValue,
82 3
            '>' => $value > $compareValue,
83 3
            '>=' => $value >= $compareValue,
84 3
            '<' => $value < $compareValue,
85 3
            '<=' => $value <= $compareValue,
86 30
            default => false,
87
        };
88
    }
89
}
90