Passed
Pull Request — master (#566)
by Sergei
03:12
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 RulesTypeWithoutNull from ValidatorInterface
61
 * @psalm-import-type NormalizedRulesArrayType 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
    SkipOnErrorInterface,
68 1
    WhenInterface,
69 1
    SkipOnEmptyInterface,
70 1
    PropagateOptionsInterface,
71
    AfterInitAttributeEventInterface
72 1
{
73 1
    use SkipOnEmptyTrait;
74
    use SkipOnErrorTrait;
75 1
    use WhenTrait;
76 1
77
    /**
78
     * @var array Rules to apply for each element of the validated iterable.
79 1
     * @psalm-var NormalizedRulesArrayType
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
     * @param string $incorrectInputMessage Error message used when validation fails because the validated value is not
86 1
     * an iterable.
87
     *
88
     * You may use the following placeholders in the message:
89
     *
90
     * - `{attribute}`: the translated label of the attribute being validated.
91
     * - `{type}`: the type of the value being validated.
92 18
     * @param string $incorrectInputKeyMessage Error message used when validation fails because the validated iterable
93
     * contains invalid keys. Only integer and string keys are allowed.
94 18
     *
95
     * You may use the following placeholders in the message:
96
     *
97 5
     * - `{attribute}`: the translated label of the attribute being validated.
98
     * - `{type}`: the type of the iterable key being validated.
99 5
     * @param bool|callable|null $skipOnEmpty Whether to skip this `Each` rule with all defined {@see $rules} if the
100
     * validated value is empty / not passed. See {@see SkipOnEmptyInterface}.
101
     * @param bool $skipOnError Whether to skip this `Each` rule with all defined {@see $rules} if any of the previous
102 3
     * rules gave an error. See {@see SkipOnErrorInterface}.
103
     * @param Closure|null $when A callable to define a condition for applying this `Each` rule with all defined
104 3
     * {@see $rules}. See {@see WhenInterface}.
105
     *
106
     * @psalm-param RulesTypeWithoutNull $rules
107 3
     * @psalm-param WhenType $when
108
     */
109
    public function __construct(
110
        callable|iterable|object|string $rules = [],
111
        private string $incorrectInputMessage = 'Value must be array or iterable.',
112
        private string $incorrectInputKeyMessage = 'Every iterable key must have an integer or a string type.',
113
        private mixed $skipOnEmpty = null,
114
        private bool $skipOnError = false,
115
        private Closure|null $when = null,
116
    ) {
117
        $this->rules = RulesNormalizer::normalizeToArray($rules);
118 3
    }
119
120
    public function getName(): string
121
    {
122 3
        return 'each';
123
    }
124
125 3
    public function propagateOptions(): void
126 3
    {
127 3
        foreach ($this->rules as $key => $rules) {
128
            $this->rules[$key] = PropagateOptionsHelper::propagate($this, $rules);
129
        }
130
    }
131 18
132
    /**
133 18
     * Gets a set of rules that needs to be applied to each element of the validated iterable.
134
     *
135
     * @return array A set of rules.
136
     *
137
     * @psalm-return NormalizedRulesArrayType
138
     *
139
     * @see $rules
140
     */
141
    public function getRules(): array
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' => RulesDumper::asArray($this->rules),
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 $rules) {
202
            foreach ($rules as $rule) {
203
                if ($rule instanceof AfterInitAttributeEventInterface) {
204
                    $rule->afterInitAttribute(
205
                        $object,
206
                        $target === Attribute::TARGET_CLASS ? Attribute::TARGET_PROPERTY : $target
207
                    );
208
                }
209
            }
210
        }
211
    }
212
}
213