Passed
Pull Request — master (#496)
by
unknown
02:41
created

Each::dumpRulesAsArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
cc 1
ccs 0
cts 0
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Closure;
9
use JetBrains\PhpStorm\ArrayShape;
10
use Yiisoft\Validator\AfterInitAttributeEventInterface;
11
use Yiisoft\Validator\DataSet\ObjectDataSet;
12
use Yiisoft\Validator\Helper\PropagateOptionsHelper;
13
use Yiisoft\Validator\Helper\RulesNormalizer;
14
use Yiisoft\Validator\PropagateOptionsInterface;
15
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
16
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
17
use Yiisoft\Validator\Rule\Trait\WhenTrait;
18
use Yiisoft\Validator\RuleInterface;
19
use Yiisoft\Validator\Helper\RulesDumper;
20
use Yiisoft\Validator\RuleWithOptionsInterface;
21
use Yiisoft\Validator\SkipOnEmptyInterface;
22
use Yiisoft\Validator\SkipOnErrorInterface;
23
use Yiisoft\Validator\WhenInterface;
24
25
/**
26
 * Allows to define a set of rules for validating each element of an iterable.
27
 *
28
 * An example for simple iterable that can be used to validate RGB point:
29
 *
30
 * ```php
31
 * $rules = [
32
 *     new Count(exactly: 3), // Not required for using with `Each`.
33
 *     new Each([
34
 *         new Number(min: 0, max: 255, integerOnly: true),
35
 *         // More rules can be added here.
36
 *     ]),
37
 * ];
38
 * ```
39 6
 *
40
 * When paired with {@see Nested} rule, it allows validation of related data:
41
 *
42
 * ```php
43
 * $coordinateRules = [new Number(min: -10, max: 10)];
44
 * $rule = new Each([
45
 *     new Nested([
46
 *         'coordinates.x' => $coordinateRules,
47
 *         'coordinates.y' => $coordinateRules,
48
 *     ]),
49
 * ]);
50
 * ```
51
 *
52
 * It's also possible to use DTO objects with PHP attributes, see {@see ObjectDataSet} documentation and guide for
53
 * details.
54
 *
55
 * Supports propagation of options (see {@see PropagateOptionsHelper::propagate()}).
56
 *
57 6
 * @see EachHandler Corresponding handler performing the actual validation.
58
 *
59
 * @psalm-import-type WhenType from WhenInterface
60 2
 */
61
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
62 2
final class Each implements
63
    RuleWithOptionsInterface,
64
    SkipOnErrorInterface,
65 1
    WhenInterface,
66
    SkipOnEmptyInterface,
67 1
    PropagateOptionsInterface,
68 1
    AfterInitAttributeEventInterface
69 1
{
70 1
    use SkipOnEmptyTrait;
71
    use SkipOnErrorTrait;
72 1
    use WhenTrait;
73 1
74
    /**
75 1
     * @var iterable A set of normalized rules that needs to be applied to each element of the validated iterable.
76 1
     * @psalm-var iterable<RuleInterface>
77
     */
78
    private iterable $rules;
79 1
    /**
80
     * @var RulesDumper|null A rules dumper instance used to dump {@see $rules} as array. Lazily created by
81 1
     * {@see getRulesDumper()} only when it's needed.
82 1
     */
83
    private ?RulesDumper $rulesDumper = null;
84
85
    /**
86 1
     * @param callable|iterable|RuleInterface $rules A set of rules that needs to be applied to each element of the
87
     * validated iterable. They will be normalized using {@see RulesNormalizer}.
88
     * @param string $incorrectInputMessage Error message used when validation fails because the validated value is not
89
     * an iterable.
90
     *
91
     * You may use the following placeholders in the message:
92 18
     *
93
     * - `{attribute}`: the translated label of the attribute being validated.
94 18
     * - `{type}`: the type of the value being validated.
95
     * @param string $incorrectInputKeyMessage Error message used when validation fails because the validated iterable
96
     * contains invalid keys. Only integer and string keys are allowed.
97 5
     *
98
     * You may use the following placeholders in the message:
99 5
     *
100
     * - `{attribute}`: the translated label of the attribute being validated.
101
     * - `{type}`: the type of the iterable key being validated.
102 3
     * @param bool|callable|null $skipOnEmpty Whether to skip this `Each` rule with all defined {@see $rules} if the
103
     * validated value is empty / not passed. See {@see SkipOnEmptyInterface}.
104 3
     * @param bool $skipOnError Whether to skip this `Each` rule with all defined {@see $rules} if any of the previous
105
     * rules gave an error. See {@see SkipOnErrorInterface}.
106
     * @param Closure|null $when A callable to define a condition for applying this `Each` rule with all defined
107 3
     * {@see $rules}. See {@see WhenInterface}.
108
     * @psalm-param WhenType $when
109
     */
110
    public function __construct(
111
        /**
112
         * @param callable|iterable<callable|RuleInterface>|RuleInterface $rules
113
         */
114
        iterable|callable|RuleInterface $rules = [],
115
        private string $incorrectInputMessage = 'Value must be array or iterable.',
116
        private string $incorrectInputKeyMessage = 'Every iterable key must have an integer or a string type.',
117
        private mixed $skipOnEmpty = null,
118 3
        private bool $skipOnError = false,
119
        private Closure|null $when = null,
120
    ) {
121
        $this->rules = RulesNormalizer::normalizeList($rules);
122 3
    }
123
124
    public function getName(): string
125 3
    {
126 3
        return 'each';
127 3
    }
128
129
    public function propagateOptions(): void
130
    {
131 18
        $this->rules = PropagateOptionsHelper::propagate($this, $this->rules);
132
    }
133 18
134
    /**
135
     * Gets a set of normalized rules that needs to be applied to each element of the validated iterable.
136
     *
137
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]> A set of rules.
138
     *
139
     * @see $rules
140
     */
141
    public function getRules(): iterable
142
    {
143
        return $this->rules;
144
    }
145
146
    /**
147
     * Gets error message used when validation fails because the validated value is not an iterable.
148
     *
149
     * @return string Error message / template.
150
     *
151
     * @see $incorrectInputMessage
152
     */
153
    public function getIncorrectInputMessage(): string
154
    {
155
        return $this->incorrectInputMessage;
156
    }
157
158
    /**
159
     * Error message used when validation fails because the validated iterable contains invalid keys.
160
     *
161
     * @return string Error message / template.
162
     *
163
     * @see $incorrectInputKeyMessage
164
     */
165
    public function getIncorrectInputKeyMessage(): string
166
    {
167
        return $this->incorrectInputKeyMessage;
168
    }
169
170
    #[ArrayShape([
171
        'incorrectInputMessage' => 'array',
172
        'incorrectInputKeyMessage' => 'array',
173
        'skipOnEmpty' => 'bool',
174
        'skipOnError' => 'bool',
175
        'rules' => 'array',
176
    ])]
177
    public function getOptions(): array
178
    {
179
        return [
180
            'incorrectInputMessage' => [
181
                'template' => $this->incorrectInputMessage,
182
                'parameters' => [],
183
            ],
184
            'incorrectInputKeyMessage' => [
185
                'template' => $this->incorrectInputKeyMessage,
186
                'parameters' => [],
187
            ],
188
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
189
            'skipOnError' => $this->skipOnError,
190
            'rules' => $this->dumpRulesAsArray(),
191
        ];
192
    }
193
194
    public function getHandler(): string
195
    {
196
        return EachHandler::class;
197
    }
198
199
    public function afterInitAttribute(object $object, int $target): void
200
    {
201
        foreach ($this->rules as $rule) {
202
            if ($rule instanceof AfterInitAttributeEventInterface) {
203
                $rule->afterInitAttribute(
204
                    $object,
205
                    $target === Attribute::TARGET_CLASS ? Attribute::TARGET_PROPERTY : $target
206
                );
207
            }
208
        }
209
    }
210
211
    /**
212
     * Dumps defined {@see $rules} to array.
213
     *
214
     * @return array The array of rules with their options.
215
     */
216
    protected function dumpRulesAsArray(): array
217
    {
218
        return $this->getRulesDumper()->asArray($this->getRules());
219
    }
220
221
    /**
222
     * Returns existing rules dumper instance for dumping defined {@see $rules} as array if it's already set. If not set
223
     * yet, creates the new instance first.
224
     *
225
     * @return RulesDumper A rules dumper instance.
226
     *
227
     * @see $rulesDumper
228
     */
229
    private function getRulesDumper(): RulesDumper
230
    {
231
        if ($this->rulesDumper === null) {
232
            $this->rulesDumper = new RulesDumper();
233
        }
234
235
        return $this->rulesDumper;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->rulesDumper could return the type null which is incompatible with the type-hinted return Yiisoft\Validator\Helper\RulesDumper. Consider adding an additional type-check to rule them out.
Loading history...
236
    }
237
}
238