Passed
Pull Request — master (#248)
by Alexander
02:21
created

Compare   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 140
Duplicated Lines 0 %

Test Coverage

Coverage 96.77%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 50
c 1
b 0
f 0
dl 0
loc 140
ccs 30
cts 31
cp 0.9677
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 46 2
A getType() 0 3 1
A getOperator() 0 3 1
A getMessage() 0 10 1
A getTargetAttribute() 0 3 1
A getTargetValue() 0 3 1
A getOptions() 0 26 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Closure;
9
use InvalidArgumentException;
10
use JetBrains\PhpStorm\ArrayShape;
11
use RuntimeException;
12
use Yiisoft\Validator\ParametrizedRuleInterface;
13
use Yiisoft\Validator\BeforeValidationInterface;
14
use Yiisoft\Validator\Rule\Trait\HandlerClassNameTrait;
15
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait;
16
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
17
use Yiisoft\Validator\ValidationContext;
18
19
abstract class Compare implements ParametrizedRuleInterface, BeforeValidationInterface
20
{
21
    use BeforeValidationTrait;
22
    use HandlerClassNameTrait;
23
    use RuleNameTrait;
24
25
    /**
26
     * Constant for specifying the comparison as string values.
27
     * No conversion will be done before comparison.
28
     *
29
     * @see $type
30
     */
31
    public const TYPE_STRING = 'string';
32
    /**
33
     * Constant for specifying the comparison as numeric values.
34
     * String values will be converted into numbers before comparison.
35
     *
36
     * @see $type
37
     */
38
    public const TYPE_NUMBER = 'number';
39
40
    private array $validOperators = [
41
        '==' => 1,
42
        '===' => 1,
43
        '!=' => 1,
44
        '!==' => 1,
45
        '>' => 1,
46
        '>=' => 1,
47
        '<' => 1,
48
        '<=' => 1,
49
    ];
50
51 15
    public function __construct(
52
        /**
53
         * @var mixed The constant value to be compared with. When both this property
54
         * and {@see $targetAttribute} are set, this property takes precedence.
55
         */
56
        private $targetValue = null,
57
        /**
58
         * @var string|null The name of the attribute to be compared with. When both this property
59
         * and {@see $targetValue} are set, the {@see $targetValue} takes precedence.
60
         *
61
         * @see $targetValue
62
         */
63
        private ?string $targetAttribute = null,
64
        /**
65
         * @var string|null User-defined error message.
66
         */
67
        private ?string $message = null,
68
        /**
69
         * @var string The type of the values being compared.
70
         */
71
        private string $type = self::TYPE_STRING,
72
        /**
73
         * @var string The operator for comparison. The following operators are supported:
74
         *
75
         * - `==`: check if two values are equal. The comparison is done is non-strict mode.
76
         * - `===`: check if two values are equal. The comparison is done is strict mode.
77
         * - `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
78
         * - `!==`: check if two values are NOT equal. The comparison is done is strict mode.
79
         * - `>`: check if value being validated is greater than the value being compared with.
80
         * - `>=`: check if value being validated is greater than or equal to the value being compared with.
81
         * - `<`: check if value being validated is less than the value being compared with.
82
         * - `<=`: check if value being validated is less than or equal to the value being compared with.
83
         *
84
         * When you want to compare numbers, make sure to also change @see $type} to
85
         * {@see TYPE_NUMBER}.
86
         */
87
        private string $operator = '==',
88
        private bool $skipOnEmpty = false,
89
        private bool $skipOnError = false,
90
        /**
91
         * @var Closure(mixed, ValidationContext):bool|null
92
         */
93
        private ?Closure $when = null,
94
    ) {
95 15
        if (!isset($this->validOperators[$operator])) {
96
            throw new InvalidArgumentException("Operator \"$operator\" is not supported.");
97
        }
98
    }
99
100 65
    public function getTargetValue(): mixed
101
    {
102 65
        return $this->targetValue;
103
    }
104
105 65
    public function getTargetAttribute(): ?string
106
    {
107 65
        return $this->targetAttribute;
108
    }
109
110 65
    public function getType(): string
111
    {
112 65
        return $this->type;
113
    }
114
115 65
    public function getOperator(): string
116
    {
117 65
        return $this->operator;
118
    }
119
120 80
    public function getMessage(): string
121
    {
122 80
        return $this->message ?? match ($this->operator) {
123 17
            '==', '===' => 'Value must be equal to "{targetValueOrAttribute}".',
124 16
            '!=', '!==' => 'Value must not be equal to "{targetValueOrAttribute}".',
125 8
            '>' => 'Value must be greater than "{targetValueOrAttribute}".',
126 8
            '>=' => 'Value must be greater than or equal to "{targetValueOrAttribute}".',
127 8
            '<' => 'Value must be less than "{targetValueOrAttribute}".',
128 8
            '<=' => 'Value must be less than or equal to "{targetValueOrAttribute}".',
129 80
            default => throw new RuntimeException("Unknown operator: $this->operator."),
130
        };
131
    }
132
133 45
    #[ArrayShape([
134
        'targetValue' => 'mixed',
135
        'targetAttribute' => 'string|null',
136
        'message' => 'array',
137
        'type' => 'string',
138
        'operator' => 'string',
139
        'skipOnEmpty' => 'bool',
140
        'skipOnError' => 'bool',
141
    ])]
142
    public function getOptions(): array
143
    {
144
        return [
145 45
            'targetValue' => $this->targetValue,
146 45
            'targetAttribute' => $this->targetAttribute,
147
            'message' => [
148 45
                'message' => $this->getMessage(),
149
                'parameters' => [
150 45
                    'targetValue' => $this->targetValue,
151 45
                    'targetAttribute' => $this->targetAttribute,
152 45
                    'targetValueOrAttribute' => $this->targetValue ?? $this->targetAttribute,
153
                ],
154
            ],
155 45
            'type' => $this->type,
156 45
            'operator' => $this->operator,
157 45
            'skipOnEmpty' => $this->skipOnEmpty,
158 45
            'skipOnError' => $this->skipOnError,
159
        ];
160
    }
161
}
162