Each::getIncorrectInputKeyMessage()   A
last analyzed

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
dl 0
loc 3
ccs 0
cts 0
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
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\DumpedRuleInterface;
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(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
    DumpedRuleInterface,
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
     *
80
     * @psalm-var NormalizedRulesMap
81 1
     */
82 1
    private array $rules;
83
84
    /**
85
     * @param callable|iterable|object|string $rules Rules to apply for each element of the validated iterable.
86 1
     * They will be normalized using {@see RulesNormalizer}.
87
     *
88
     * @psalm-param RawRules $rules
89
     *
90
     * @param string $incorrectInputMessage Error message used when validation fails because the validated value is not
91
     * an iterable.
92 18
     *
93
     * You may use the following placeholders in the message:
94 18
     *
95
     * - `{attribute}`: the translated label of the attribute being validated.
96
     * - `{type}`: the type of the value being validated.
97 5
     * @param string $incorrectInputKeyMessage Error message used when validation fails because the validated iterable
98
     * contains invalid keys. Only integer and string keys are allowed.
99 5
     *
100
     * You may use the following placeholders in the message:
101
     *
102 3
     * - `{attribute}`: the translated label of the attribute being validated.
103
     * - `{type}`: the type of the iterable key being validated.
104 3
     * @param bool|callable|null $skipOnEmpty Whether to skip this `Each` rule with all defined {@see $rules} if the
105
     * validated value is empty / not passed. See {@see SkipOnEmptyInterface}.
106
     * @param bool $skipOnError Whether to skip this `Each` rule with all defined {@see $rules} if any of the previous
107 3
     * rules gave an error. See {@see SkipOnErrorInterface}.
108
     * @param Closure|null $when A callable to define a condition for applying this `Each` rule with all defined
109
     * {@see $rules}. See {@see WhenInterface}.
110
     *
111
     * @psalm-param WhenType $when
112
     */
113
    public function __construct(
114
        callable|iterable|object|string $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::normalize($rules);
122 3
    }
123
124
    public function getName(): string
125 3
    {
126 3
        return self::class;
127 3
    }
128
129
    public function propagateOptions(): void
130
    {
131 18
        foreach ($this->rules as $key => $attributeRules) {
132
            $this->rules[$key] = PropagateOptionsHelper::propagate($this, $attributeRules);
133 18
        }
134
    }
135
136
    /**
137
     * Gets a set of rules that needs to be applied to each element of the validated iterable.
138
     *
139
     * @return array A set of rules.
140
     *
141
     * @psalm-return NormalizedRulesMap
142
     *
143
     * @see $rules
144
     */
145
    public function getRules(): array
146
    {
147
        return $this->rules;
148
    }
149
150
    /**
151
     * Gets error message used when validation fails because the validated value is not an iterable.
152
     *
153
     * @return string Error message / template.
154
     *
155
     * @see $incorrectInputMessage
156
     */
157
    public function getIncorrectInputMessage(): string
158
    {
159
        return $this->incorrectInputMessage;
160
    }
161
162
    /**
163
     * Error message used when validation fails because the validated iterable contains invalid keys.
164
     *
165
     * @return string Error message / template.
166
     *
167
     * @see $incorrectInputKeyMessage
168
     */
169
    public function getIncorrectInputKeyMessage(): string
170
    {
171
        return $this->incorrectInputKeyMessage;
172
    }
173
174
    #[ArrayShape([
175
        'incorrectInputMessage' => 'array',
176
        'incorrectInputKeyMessage' => 'array',
177
        'skipOnEmpty' => 'bool',
178
        'skipOnError' => 'bool',
179
        'rules' => 'array',
180
    ])]
181
    public function getOptions(): array
182
    {
183
        return [
184
            'incorrectInputMessage' => [
185
                'template' => $this->incorrectInputMessage,
186
                'parameters' => [],
187
            ],
188
            'incorrectInputKeyMessage' => [
189
                'template' => $this->incorrectInputKeyMessage,
190
                'parameters' => [],
191
            ],
192
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
193
            'skipOnError' => $this->skipOnError,
194
            'rules' => RulesDumper::asArray($this->rules),
195
        ];
196
    }
197
198
    public function getHandler(): string
199
    {
200
        return EachHandler::class;
201
    }
202
203
    public function afterInitAttribute(object $object): void
204
    {
205
        foreach ($this->rules as $attributeRules) {
206
            foreach ($attributeRules as $rule) {
207
                if ($rule instanceof AfterInitAttributeEventInterface) {
208
                    $rule->afterInitAttribute($object);
209
                }
210
            }
211
        }
212
    }
213
}
214