Passed
Push — master ( c89a4d...ce7b1b )
by
unknown
02:57
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\Helper\RulesDumper;
19
use Yiisoft\Validator\RuleWithOptionsInterface;
20
use Yiisoft\Validator\SkipOnEmptyInterface;
21
use Yiisoft\Validator\SkipOnErrorInterface;
22
use Yiisoft\Validator\ValidatorInterface;
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 color:
29
 *
30
 * ```php
31
 * $rules = [
32
 *     new Count(exactly: 3), // Not required for using with `Each`.
33
 *     new Each([
34
 *         new Integer(min: 0, max: 255),
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()} for available options and
56
 * requirements).
57 6
 *
58
 * @see EachHandler Corresponding handler performing the actual validation.
59
 *
60 2
 * @psalm-import-type RawRules from ValidatorInterface
61
 * @psalm-import-type NormalizedRulesMap from RulesNormalizer
62 2
 * @psalm-import-type WhenType from WhenInterface
63
 */
64
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
65 1
final class Each implements
66
    RuleWithOptionsInterface,
67 1
    SkipOnEmptyInterface,
68 1
    SkipOnErrorInterface,
69 1
    WhenInterface,
70 1
    PropagateOptionsInterface,
71
    AfterInitAttributeEventInterface
72 1
{
73 1
    use SkipOnEmptyTrait;
74
    use SkipOnErrorTrait;
75 1
    use WhenTrait;
76 1
77
    /**
78
     * @var array Normalized rules to apply for each element of the validated iterable.
79 1
     * @psalm-var NormalizedRulesMap
80
     */
81 1
    private array $rules;
82 1
83
    /**
84
     * @param callable|iterable|object|string $rules Rules to apply for each element of the validated iterable.
85
     * They will be normalized using {@see RulesNormalizer}.
86 1
     * @psalm-param RawRules $rules
87
     *
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
        callable|iterable|object|string $rules = [],
112
        private string $incorrectInputMessage = 'Value must be array or iterable.',
113
        private string $incorrectInputKeyMessage = 'Every iterable key must have an integer or a string type.',
114
        private mixed $skipOnEmpty = null,
115
        private bool $skipOnError = false,
116
        private Closure|null $when = null,
117
    ) {
118 3
        $this->rules = RulesNormalizer::normalize($rules);
119
    }
120
121
    public function getName(): string
122 3
    {
123
        return 'each';
124
    }
125 3
126 3
    public function propagateOptions(): void
127 3
    {
128
        foreach ($this->rules as $key => $rules) {
129
            $this->rules[$key] = PropagateOptionsHelper::propagate($this, $rules);
130
        }
131 18
    }
132
133 18
    /**
134
     * Gets a set of rules that needs to be applied to each element of the validated iterable.
135
     *
136
     * @return array A set of rules.
137
     *
138
     * @psalm-return NormalizedRulesMap
139
     *
140
     * @see $rules
141
     */
142
    public function getRules(): array
143
    {
144
        return $this->rules;
145
    }
146
147
    /**
148
     * Gets error message used when validation fails because the validated value is not an iterable.
149
     *
150
     * @return string Error message / template.
151
     *
152
     * @see $incorrectInputMessage
153
     */
154
    public function getIncorrectInputMessage(): string
155
    {
156
        return $this->incorrectInputMessage;
157
    }
158
159
    /**
160
     * Error message used when validation fails because the validated iterable contains invalid keys.
161
     *
162
     * @return string Error message / template.
163
     *
164
     * @see $incorrectInputKeyMessage
165
     */
166
    public function getIncorrectInputKeyMessage(): string
167
    {
168
        return $this->incorrectInputKeyMessage;
169
    }
170
171
    #[ArrayShape([
172
        'incorrectInputMessage' => 'array',
173
        'incorrectInputKeyMessage' => 'array',
174
        'skipOnEmpty' => 'bool',
175
        'skipOnError' => 'bool',
176
        'rules' => 'array',
177
    ])]
178
    public function getOptions(): array
179
    {
180
        return [
181
            'incorrectInputMessage' => [
182
                'template' => $this->incorrectInputMessage,
183
                'parameters' => [],
184
            ],
185
            'incorrectInputKeyMessage' => [
186
                'template' => $this->incorrectInputKeyMessage,
187
                'parameters' => [],
188
            ],
189
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
190
            'skipOnError' => $this->skipOnError,
191
            'rules' => RulesDumper::asArray($this->rules),
192
        ];
193
    }
194
195
    public function getHandler(): string
196
    {
197
        return EachHandler::class;
198
    }
199
200
    public function afterInitAttribute(object $object, int $target): void
201
    {
202
        foreach ($this->rules as $attributeRules) {
203
            foreach ($attributeRules as $rule) {
204
                if ($rule instanceof AfterInitAttributeEventInterface) {
205
                    $rule->afterInitAttribute(
206
                        $object,
207
                        $target === Attribute::TARGET_CLASS ? Attribute::TARGET_PROPERTY : $target
208
                    );
209
                }
210
            }
211
        }
212
    }
213
}
214