Passed
Pull Request — master (#246)
by Rustam
02:18
created

CompareTo::getCompareAttribute()   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
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 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
/**
20
 * Compares the specified value with another value.
21
 *
22
 * The value being compared with a constant {@see CompareTo::$compareValue}, which is set
23
 * in the constructor.
24
 *
25
 * It supports different comparison operators, specified
26
 * via the {@see CompareTo::$operator}.
27
 *
28
 * The default comparison function is based on string values, which means the values
29
 * are compared byte by byte. When comparing numbers, make sure to change {@see CompareTo::$type} to
30
 * {@see CompareTo::TYPE_NUMBER} to enable numeric comparison.
31
 */
32
#[Attribute(Attribute::TARGET_PROPERTY)]
33
final class CompareTo implements ParametrizedRuleInterface, BeforeValidationInterface
34
{
35
    use BeforeValidationTrait;
36
    use HandlerClassNameTrait;
37
    use RuleNameTrait;
38
39
    /**
40
     * Constant for specifying the comparison as string values.
41
     * No conversion will be done before comparison.
42
     *
43
     * @see CompareTo::$type
44
     */
45
    public const TYPE_STRING = 'string';
46
    /**
47
     * Constant for specifying the comparison as numeric values.
48
     * String values will be converted into numbers before comparison.
49
     *
50
     * @see CompareTo::$type
51
     */
52
    public const TYPE_NUMBER = 'number';
53
54
    private array $validOperators = [
55
        '==' => 1,
56
        '===' => 1,
57
        '!=' => 1,
58
        '!==' => 1,
59
        '>' => 1,
60
        '>=' => 1,
61
        '<' => 1,
62
        '<=' => 1,
63
    ];
64
65 2
    public function __construct(
66
        /**
67
         * @var mixed the constant value to be compared with.
68
         */
69
        private $compareValue = null,
70
        /**
71
         * @var string|null the name of the attribute to be compared with.
72
         */
73
        private ?string $compareAttribute = null,
74
        /**
75
         * @var string|null user-defined error message
76
         */
77
        private ?string $message = null,
78
        /**
79
         * @var string the type of the values being compared.
80
         */
81
        private string $type = self::TYPE_STRING,
82
        /**
83
         * @var string the operator for comparison. The following operators are supported:
84
         *
85
         * - `==`: check if two values are equal. The comparison is done is non-strict mode.
86
         * - `===`: check if two values are equal. The comparison is done is strict mode.
87
         * - `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
88
         * - `!==`: check if two values are NOT equal. The comparison is done is strict mode.
89
         * - `>`: check if value being validated is greater than the value being compared with.
90
         * - `>=`: check if value being validated is greater than or equal to the value being compared with.
91
         * - `<`: check if value being validated is less than the value being compared with.
92
         * - `<=`: check if value being validated is less than or equal to the value being compared with.
93
         *
94
         * When you want to compare numbers, make sure to also change @see CompareTo::$type} to
95
         * {@see CompareTo::TYPE_NUMBER}.
96
         */
97
        private string $operator = '==',
98
        private bool $skipOnEmpty = false,
99
        private bool $skipOnError = false,
100
        /**
101
         * @var Closure(mixed, ValidationContext):bool|null
102
         */
103
        private ?Closure $when = null,
104
    ) {
105 2
        if (!isset($this->validOperators[$operator])) {
106
            throw new InvalidArgumentException("Operator \"$operator\" is not supported.");
107
        }
108
    }
109
110
    /**
111
     * @return mixed
112
     */
113 36
    public function getCompareValue(): mixed
114
    {
115 36
        return $this->compareValue;
116
    }
117
118
    /**
119
     * @return string|null
120
     */
121 36
    public function getCompareAttribute(): ?string
122
    {
123 36
        return $this->compareAttribute;
124
    }
125
126
    /**
127
     * @return string
128
     */
129 36
    public function getType(): string
130
    {
131 36
        return $this->type;
132
    }
133
134
    /**
135
     * @return string
136
     */
137 36
    public function getOperator(): string
138
    {
139 36
        return $this->operator;
140
    }
141
142 27
    public function getMessage(): string
143
    {
144 27
        return $this->message ?? match ($this->operator) {
145 9
            '==', '===' => 'Value must be equal to "{compareValueOrAttribute}".',
146 7
            '!=', '!==' => 'Value must not be equal to "{compareValueOrAttribute}".',
147 2
            '>' => 'Value must be greater than "{compareValueOrAttribute}".',
148 2
            '>=' => 'Value must be greater than or equal to "{compareValueOrAttribute}".',
149 2
            '<' => 'Value must be less than "{compareValueOrAttribute}".',
150 2
            '<=' => 'Value must be less than or equal to "{compareValueOrAttribute}".',
151 27
            default => throw new RuntimeException("Unknown operator: {$this->operator}"),
152
        };
153
    }
154
155 9
    #[ArrayShape([
156
        'compareValue' => 'mixed',
157
        'compareAttribute' => '',
158
        'message' => 'array',
159
        'type' => 'string',
160
        'operator' => 'string',
161
        'skipOnEmpty' => 'bool',
162
        'skipOnError' => 'bool',
163
    ])]
164
    public function getOptions(): array
165
    {
166
        return [
167 9
            'compareValue' => $this->compareValue,
168 9
            'compareAttribute' => $this->compareAttribute,
169
            'message' => [
170 9
                'message' => $this->getMessage(),
171
                'parameters' => [
172 9
                    'compareValue' => $this->compareValue,
173 9
                    'compareAttribute' => $this->compareAttribute,
174 9
                    'compareValueOrAttribute' => $this->compareValue ?? $this->compareAttribute,
175
                ],
176
            ],
177 9
            'type' => $this->type,
178 9
            'operator' => $this->operator,
179 9
            'skipOnEmpty' => $this->skipOnEmpty,
180 9
            'skipOnError' => $this->skipOnError,
181
        ];
182
    }
183
}
184