Passed
Pull Request — master (#222)
by Alexander
04:26 queued 02:14
created

CompareTo::getMessage()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 10.0145

Importance

Changes 0
Metric Value
cc 10
eloc 19
nc 10
nop 0
dl 0
loc 23
ccs 18
cts 19
cp 0.9474
crap 10.0145
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\PreValidatableRuleInterface;
13
use Yiisoft\Validator\Rule\Trait\PreValidatableTrait;
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_TRAIT, expecting T_STRING or '{' on line 13 at column 27
Loading history...
14
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
15
use Yiisoft\Validator\Rule\Trait\HandlerClassNameTrait;
16
use Yiisoft\Validator\ParametrizedRuleInterface;
17
18
/**
19
 * Compares the specified value with another value.
20
 *
21
 * The value being compared with a constant {@see CompareTo::$compareValue}, which is set
22
 * in the constructor.
23
 *
24
 * It supports different comparison operators, specified
25
 * via the {@see CompareTo::$operator}.
26
 *
27
 * The default comparison function is based on string values, which means the values
28
 * are compared byte by byte. When comparing numbers, make sure to change {@see CompareTo::$type} to
29
 * {@see CompareTo::TYPE_NUMBER} to enable numeric comparison.
30
 */
31
#[Attribute(Attribute::TARGET_PROPERTY)]
32
final class CompareTo implements ParametrizedRuleInterface, PreValidatableRuleInterface
33
{
34
    use HandlerClassNameTrait;
35
    use PreValidatableTrait;
36
    use RuleNameTrait;
37
38
    /**
39
     * Constant for specifying the comparison as string values.
40
     * No conversion will be done before comparison.
41
     *
42
     * @see $type
43
     */
44
    public const TYPE_STRING = 'string';
45
    /**
46
     * Constant for specifying the comparison as numeric values.
47
     * String values will be converted into numbers before comparison.
48
     *
49
     * @see $type
50
     */
51
    public const TYPE_NUMBER = 'number';
52
    private array $validOperators = [
53
        '==' => 1,
54
        '===' => 1,
55
        '!=' => 1,
56
        '!==' => 1,
57
        '>' => 1,
58
        '>=' => 1,
59
        '<' => 1,
60
        '<=' => 1,
61
    ];
62
63 1
    public function __construct(
64
        /**
65
         * @var mixed the constant value to be compared with.
66
         */
67
        private $compareValue,
68
        /**
69
         * @var string|null user-defined error message
70
         */
71
        private ?string $message = null,
72
        /**
73
         * @var string the type of the values being compared.
74
         */
75
        private string $type = self::TYPE_STRING,
76
        /**
77
         * @var string the operator for comparison. The following operators are supported:
78
         *
79
         * - `==`: check if two values are equal. The comparison is done is non-strict mode.
80
         * - `===`: check if two values are equal. The comparison is done is strict mode.
81
         * - `!=`: check if two values are NOT equal. The comparison is done is non-strict mode.
82
         * - `!==`: check if two values are NOT equal. The comparison is done is strict mode.
83
         * - `>`: check if value being validated is greater than the value being compared with.
84
         * - `>=`: check if value being validated is greater than or equal to the value being compared with.
85
         * - `<`: check if value being validated is less than the value being compared with.
86
         * - `<=`: check if value being validated is less than or equal to the value being compared with.
87
         *
88
         * When you want to compare numbers, make sure to also chabge @see CompareTo::$type} to
89
         * {@see CompareTo::TYPE_NUMBER}.
90
         */
91
        private string $operator = '==',
92
        private bool $skipOnEmpty = false,
93
        private bool $skipOnError = false,
94
        private ?Closure $when = null,
95
    ) {
96 1
        if (!isset($this->validOperators[$operator])) {
97
            throw new InvalidArgumentException("Operator \"$operator\" is not supported.");
98
        }
99
    }
100
101
    /**
102
     * @return mixed
103
     */
104 30
    public function getCompareValue(): mixed
105
    {
106 30
        return $this->compareValue;
107
    }
108
109
    /**
110
     * @return string
111
     */
112 30
    public function getType(): string
113
    {
114 30
        return $this->type;
115
    }
116
117
    /**
118
     * @return string
119
     */
120 30
    public function getOperator(): string
121
    {
122 30
        return $this->operator;
123
    }
124
125 22
    public function getMessage(): string
126
    {
127 22
        return $this->message ?? match ($this->operator) {
128 6
            '==', '===' => 'Value must be equal to "{compareValue}".',
129 7
            '!=', '!==' => 'Value must not be equal to "{compareValue}".',
130 2
            '>' => 'Value must be greater than "{compareValue}".',
131 2
            '>=' => 'Value must be greater than or equal to "{compareValue}".',
132 2
            '<' => 'Value must be less than "{compareValue}".',
133 1
            '<=' => 'Value must be less than or equal to "{compareValue}".',
134 22
            default => throw new RuntimeException("Unknown operator: {$this->operator}"),
135
        };
136
    }
137
138 7
    #[ArrayShape([
139
        'compareValue' => '',
140
        'message' => 'array',
141
        'type' => 'string',
142
        'operator' => 'string',
143
        'skipOnEmpty' => 'bool',
144
        'skipOnError' => 'bool',
145
    ])]
146
    public function getOptions(): array
147
    {
148
        return [
149 7
            'compareValue' => $this->compareValue,
150
            'message' => [
151 7
                'message' => $this->getMessage(),
152 7
                'parameters' => ['compareValue' => $this->compareValue],
153
            ],
154 7
            'type' => $this->type,
155 7
            'operator' => $this->operator,
156 7
            'skipOnEmpty' => $this->skipOnEmpty,
157 7
            'skipOnError' => $this->skipOnError,
158
        ];
159
    }
160
}
161