Passed
Push — master ( 174075...bbc670 )
by
unknown
20:50 queued 17:58
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 13
dl 0
loc 21
ccs 9
cts 9
cp 1
crap 1
rs 10
c 2
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 ReflectionProperty;
12
use Traversable;
13
use Yiisoft\Strings\StringHelper;
14
use Yiisoft\Validator\AfterInitAttributeEventInterface;
15
use Yiisoft\Validator\DataSet\ObjectDataSet;
16
use Yiisoft\Validator\Helper\PropagateOptionsHelper;
17
use Yiisoft\Validator\PropagateOptionsInterface;
18
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
19
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
20
use Yiisoft\Validator\Rule\Trait\WhenTrait;
21
use Yiisoft\Validator\RuleInterface;
22
use Yiisoft\Validator\Helper\RulesDumper;
23
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
24
use Yiisoft\Validator\RulesProviderInterface;
25
use Yiisoft\Validator\RuleWithOptionsInterface;
26
use Yiisoft\Validator\SkipOnEmptyInterface;
27
use Yiisoft\Validator\SkipOnErrorInterface;
28
use Yiisoft\Validator\Tests\Rule\NestedTest;
29
use Yiisoft\Validator\WhenInterface;
30
31
use function array_pop;
32
use function count;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Validator\Rule\count. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
33
use function implode;
34
use function is_string;
35
use function ltrim;
36
use function rtrim;
37
use function sprintf;
38
39
/**
40
 * Used to define rules for validation of nested structures:
41
 *
42
 * - For one-to-one relation, using `Nested` rule is enough.
43
 * - One-to-many and many-to-many relations require pairing with {@see Each} rule.
44
 *
45
 * An example with blog post:
46
 *
47
 * ```php
48
 * $rules = [
49
 *     new Nested([
50
 *         'title' => [new HasLength(max: 255)],
51
 *          // One-to-one relation
52
 *         'author' => new Nested([
53
 *             'name' => [new HasLength(min: 1)],
54
 *         ]),
55
 *         // One-to-many relation
56
 *         'files' => new Each(new Nested([
57
 *             'url' => [new Url()],
58
 *         ])),
59
 *     ]);
60
 * ];
61
 * ```
62
 *
63
 * There is an alternative way to write this using dot notation and shortcuts:
64
 *
65
 * ```php
66
 * $rules = [
67
 *     new Nested([
68
 *         'title' => [new HasLength(max: 255)],
69
 *         'author.name' => [new HasLength(min: 1)],
70
 *         'files.*.url' => [new Url()],
71
 *     ]);
72
 * ];
73
 * ```
74
 *
75 26
 * For more examples please refer to the guide.
76
 *
77
 * It's also possible to use DTO objects with PHP attributes, see {@see ObjectDataSet} documentation and guide for
78
 * details.
79
 *
80
 * Supports propagation of options (see {@see PropagateOptionsHelper::propagate()} for supported options and
81
 * requirements).
82
 *
83
 * @see NestedHandler Corresponding handler performing the actual validation.
84
 *
85
 * @psalm-import-type WhenType from WhenInterface
86
 */
87
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
88
final class Nested implements
89
    RuleWithOptionsInterface,
90
    SkipOnErrorInterface,
91
    WhenInterface,
92
    SkipOnEmptyInterface,
93
    PropagateOptionsInterface,
94
    AfterInitAttributeEventInterface
95
{
96
    use SkipOnEmptyTrait;
97
    use SkipOnErrorTrait;
98
    use WhenTrait;
99
100
    /**
101
     * A character acting as a separator when using alternative (short) syntax.
102
     */
103
    private const SEPARATOR = '.';
104
    /**
105
     * A character acting as a shortcut when using alternative (short) syntax with {@see Nested} and {@see Each}
106
     * combinations.
107
     */
108
    private const EACH_SHORTCUT = '*';
109
110
    /**
111 26
     * @var iterable<iterable<RuleInterface>|RuleInterface>|null
112
     */
113
    private iterable|null $rules;
114 2
115
    /**
116 2
     * @param iterable|object|string|null $rules
117
     * @param int $validatedObjectPropertyVisibility Visibility levels to use for parsed properties when validated value
118
     * is an object providing rules / data. For example: public and protected only, this means that the rest (private
119
     * ones) will be skipped. Defaults to all visibility levels (public, protected and private). See
120
     * {@see ObjectDataSet} for details on providing rules / data in validated object and {@see ObjectParser} for
121
     * overview how parsing works.
122 53
     * @psalm-param int-mask-of<ReflectionProperty::IS_*> $validatedObjectPropertyVisibility
123
     * @param int $rulesSourceClassPropertyVisibility Visibility levels to use for parsed properties when {@see $rules}
124 53
     * source is a name of the class providing rules. For example: public and protected only, this means that the rest
125
     * (private ones) will be skipped. Defaults to all visibility levels (public, protected and private). See
126
     * {@see ObjectDataSet} for details on providing rules via class and {@see ObjectParser} for overview how parsing
127 11
     * works.
128
     * @psalm-param int-mask-of<ReflectionProperty::IS_*> $rulesSourceClassPropertyVisibility
129 11
     * @param string $noRulesWithNoObjectMessage Error message used when validation fails because the validated value is
130
     * not an object and the rules were not explicitly specified via {@see $rules}:
131
     *
132 5
     * You may use the following placeholders in the message:
133
     *
134 5
     * - `{attribute}`: the translated label of the attribute being validated.
135
     * - `{type}`: the type of the value being validated.
136
     * @param string $incorrectDataSetTypeMessage Error message used when validation fails because the validated value
137 3
     * is an object providing wrong type of data (neither array nor an object).
138
     *
139 3
     * You may use the following placeholders in the message:
140
     *
141
     * - `{type}`: the type of the data set retrieved from the validated object.
142 5
     * @param string $incorrectInputMessage Error message used when validation fails because the validated value is
143
     * neither an array nor an object.
144 5
     *
145
     * You may use the following placeholders in the message:
146
     *
147 39
     * - `{attribute}`: the translated label of the attribute being validated.
148
     * - `{type}`: the type of the value being validated.
149 39
     * @param bool $requirePropertyPath Whether to require a single data item to be passed in data according to declared
150
     * nesting level structure (all keys in the sequence must be the present). Used only when validated value is an
151
     * array. Enabled by default. See {@see $noPropertyPathMessage} for customization of error message.
152 10
     * @param string $noPropertyPathMessage Error message used when validation fails because {@see $requirePropertyPath}
153
     * option was enabled and the validated array contains missing data item.
154 10
     *
155
     * You may use the following placeholders in the message:
156
     *
157
     * - `{path}`: the path of the value being validated. Can be either a simple key of integer / string type for a s
158
     * ingle nesting level or a sequence of keys concatenated using dot notation (see {@see SEPARATOR}).
159
     * - `{attribute}`: the translated label of the attribute being validated.
160 26
     * @param bool $normalizeRules Whether to enable rules normalization when {@see EACH_SHORTCUT} is used. Enabled by
161
     * default meaning shortcuts are supported. Can be disabled if they are not used to prevent additional checks and
162 26
     * improve performance.
163 16
     * @param bool $propagateOptions Whether the propagation of options is enabled (see
164
     * {@see PropagateOptionsHelper::propagate()} for supported options and requirements). Disabled by default.
165 16
     * @param bool|callable|null $skipOnEmpty Whether to skip this `Nested` rule with all defined {@see $rules} if the
166
     * validated value is empty / not passed. See {@see SkipOnEmptyInterface}.
167
     * @param bool $skipOnError Whether to skip this `Nested` rule with all defined {@see $rules} if any of the previous
168 10
     * rules gave an error. See {@see SkipOnErrorInterface}.
169 1
     * @param Closure|null $when  A callable to define a condition for applying this `Nested` rule with all defined
170 9
     * {@see $rules}. See {@see WhenInterface}.
171 4
     * @psalm-param WhenType $when
172
     */
173 5
    public function __construct(
174
        iterable|object|string|null $rules = null,
175
        private int $validatedObjectPropertyVisibility = ReflectionProperty::IS_PRIVATE
176 10
        | ReflectionProperty::IS_PROTECTED
177 8
        | ReflectionProperty::IS_PUBLIC,
178
        private int $rulesSourceClassPropertyVisibility = ReflectionProperty::IS_PRIVATE
179 8
        | ReflectionProperty::IS_PROTECTED
180 8
        | ReflectionProperty::IS_PUBLIC,
181
        private string $noRulesWithNoObjectMessage = 'Nested rule without rules can be used for objects only.',
182
        private string $incorrectDataSetTypeMessage = 'An object data set data can only have an array or an object ' .
183 7
        'type.',
184 1
        private string $incorrectInputMessage = 'The value must have an array or an object type.',
185
        private bool $requirePropertyPath = false,
186
        private string $noPropertyPathMessage = 'Property "{path}" is not found.',
187
        private bool $normalizeRules = true,
188
        private bool $propagateOptions = false,
189
        private mixed $skipOnEmpty = null,
190
        private bool $skipOnError = false,
191 10
        private Closure|null $when = null,
192
    ) {
193 10
        $this->prepareRules($rules);
194
    }
195 10
196 9
    public function getName(): string
197 7
    {
198 9
        return 'nested';
199 2
    }
200
201
    /**
202 2
     * @return iterable<iterable<RuleInterface>|RuleInterface>|null
203
     */
204
    public function getRules(): iterable|null
205 2
    {
206
        return $this->rules;
207
    }
208
209
    /**
210 8
     * Gets visibility levels to use for parsed properties when validated value is an object providing rules / data.
211
     * Defaults to all visibility levels (public, protected and private)
212
     *
213 8
     * @return int A number representing visibility levels.
214 8
     * @psalm-return int-mask-of<ReflectionProperty::IS_*>
215 8
     *
216 8
     * @see $validatedObjectPropertyVisibility
217
     */
218 8
    public function getValidatedObjectPropertyVisibility(): int
219 7
    {
220 1
        return $this->validatedObjectPropertyVisibility;
221
    }
222
223 6
    /**
224
     * Gets error message used when validation fails because the validated value is not an object and the rules were not
225
     * explicitly specified via {@see $rules}.
226
     *
227
     * @return string Error message / template.
228 6
     *
229 6
     * @see $incorrectInputMessage
230
     */
231
    public function getNoRulesWithNoObjectMessage(): string
232
    {
233
        return $this->noRulesWithNoObjectMessage;
234
    }
235
236
    /**
237
     * Gets error message used when validation fails because the validated value is an object providing wrong type of
238
     * data (neither array nor an object).
239
     *
240
     * @return string Error message / template.
241
     *
242
     * @see $incorrectDataSetTypeMessage
243
     */
244
    public function getIncorrectDataSetTypeMessage(): string
245
    {
246
        return $this->incorrectDataSetTypeMessage;
247
    }
248
249
    /**
250
     * Gets error message used when validation fails because the validated value is neither an array nor an object.
251
     *
252
     * @return string Error message / template.
253
     *
254
     * @see $incorrectInputMessage
255
     */
256 7
    public function getIncorrectInputMessage(): string
257
    {
258
        return $this->incorrectInputMessage;
259
    }
260
261
    /**
262
     * Whether to require a single data item to be passed in data according to declared nesting level structure (all
263
     * keys in the sequence must be the present). Enabled by default.
264
     *
265
     * @return bool `true` if required and `false` otherwise.
266
     *
267 7
     * @see $requirePropertyPath
268 7
     */
269
    public function isPropertyPathRequired(): bool
270
    {
271
        return $this->requirePropertyPath;
272 7
    }
273
274
    /**
275 1
     * Gets error message used when validation fails because {@see $requirePropertyPath} option was enabled and the
276
     * validated array contains missing data item.
277 1
     *
278
     * @return string Error message / template.
279
     *
280
     * @see $getNoPropertyPathMessage
281
     */
282
    public function getNoPropertyPathMessage(): string
283
    {
284
        return $this->noPropertyPathMessage;
285
    }
286 1
287 1
    /**
288 1
     * Prepares raw rules passed in the constructor for usage in handler. As a result, {@see $rules} property will
289 1
     * contain normalized rules.
290
     *
291 1
     * @param iterable|object|string|null $source Raw rules passed in the constructor.
292 1
     *
293
     * @throws InvalidArgumentException When rules' source has wrong type.
294 1
     * @throws InvalidArgumentException When source contains items that are not rules.
295 1
     */
296
    private function prepareRules(iterable|object|string|null $source): void
297
    {
298 1
        if ($source === null) {
299
            $this->rules = null;
300 1
301 1
            return;
302
        }
303
304
        if ($source instanceof RulesProviderInterface) {
305
            $rules = $source->getRules();
306 1
        } elseif (is_string($source) && class_exists($source)) {
307
            $rules = (new AttributesRulesProvider($source, $this->rulesSourceClassPropertyVisibility))->getRules();
308
        } elseif (is_iterable($source)) {
309 5
            $rules = $source;
310
        } else {
311
            throw new InvalidArgumentException(
312
                'The $rules argument passed to Nested rule can be either: a null, an object implementing ' .
313
                'RulesProviderInterface, a class string or an iterable.'
314
            );
315
        }
316
317
        self::ensureArrayHasRules($rules);
318
        $this->rules = $rules;
319
320
        if ($this->normalizeRules) {
321
            $this->normalizeRules();
322
        }
323 5
324
        if ($this->propagateOptions) {
325
            $this->propagateOptions();
326
        }
327 5
    }
328
329
    /**
330
     * Recursively checks that each item of source iterable is a valid rule instance ({@see RuleInterface}). As a
331 5
     * result, all iterables will be converted to arrays at the end.
332
     *
333
     * @psalm-assert iterable<RuleInterface> $rules
334
     *
335 5
     * @throws InvalidArgumentException When iterable contains items that are not rules.
336
     */
337
    private static function ensureArrayHasRules(iterable &$rules): void
338 5
    {
339 5
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
340 5
        /** @var mixed $rule */
341 5
        foreach ($rules as &$rule) {
342
            if (is_iterable($rule)) {
343
                self::ensureArrayHasRules($rule);
344
            } elseif (!$rule instanceof RuleInterface) {
345 53
                $message = sprintf(
346
                    'Every rule must be an instance of %s, %s given.',
347 53
                    RuleInterface::class,
348
                    get_debug_type($rule)
349
                );
350
351
                throw new InvalidArgumentException($message);
352
            }
353
        }
354
    }
355
356
    /**
357
     * Normalizes rules defined with shortcut to separate `Nested` and `Each` rules.
358
     */
359
    private function normalizeRules(): void
360
    {
361
        /** @var RuleInterface[] $rules Conversion to array is done in {@see ensureArrayHasRules()}. */
362
        $rules = $this->rules;
363
        while (true) {
364
            $breakWhile = true;
365
            $rulesMap = [];
366
367
            foreach ($rules as $valuePath => $rule) {
368
                if ($valuePath === self::EACH_SHORTCUT) {
369
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
370
                }
371
372
                $parts = StringHelper::parsePath(
373
                    (string) $valuePath,
374
                    delimiter: self::EACH_SHORTCUT,
375
                    preserveDelimiterEscaping: true
376
                );
377
                if (count($parts) === 1) {
378
                    continue;
379
                }
380
381
                /**
382
                 * Might be a bug of XDebug, because these lines are covered by tests.
383
                 *
384
                 * @see NestedTest::dataWithOtherNestedAndEach() for test cases prefixed with "withShortcut".
385
                 */
386
                // @codeCoverageIgnoreStart
387
                $breakWhile = false;
388
389
                $lastValuePath = array_pop($parts);
390
                $lastValuePath = ltrim($lastValuePath, '.');
391
                $lastValuePath = str_replace('\\' . self::EACH_SHORTCUT, self::EACH_SHORTCUT, $lastValuePath);
392
393
                $remainingValuePath = implode(self::EACH_SHORTCUT, $parts);
394
                $remainingValuePath = rtrim($remainingValuePath, self::SEPARATOR);
395
396
                if (!isset($rulesMap[$remainingValuePath])) {
397
                    $rulesMap[$remainingValuePath] = [];
398
                }
399
400
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
401
                unset($rules[$valuePath]);
402
                // @codeCoverageIgnoreEnd
403
            }
404
405
            foreach ($rulesMap as $valuePath => $nestedRules) {
406
                /**
407
                 * Might be a bug of XDebug, because this line is covered by tests.
408
                 *
409
                 * @see NestedTest::dataWithOtherNestedAndEach() for test cases prefixed with "withShortcut".
410
                 */
411
                // @codeCoverageIgnoreStart
412
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
413
                // @codeCoverageIgnoreEnd
414
            }
415
416
            if ($breakWhile === true) {
417
                break;
418
            }
419
        }
420
421
        $this->rules = $rules;
422
    }
423
424
    public function propagateOptions(): void
425
    {
426
        if ($this->rules === null) {
427
            return;
428
        }
429
430
        $rules = [];
431
432
        /**
433
         * @var int|string $attributeRulesIndex Index is either integer or string because of the array conversion in
434
         * {@see ensureArrayHasRules()}.
435
         * @var RuleInterface[] $attributeRules Conversion to array is done in {@see ensureArrayHasRules()}.
436
         */
437
        foreach ($this->rules as $attributeRulesIndex => $attributeRules) {
438
            $rules[$attributeRulesIndex] = PropagateOptionsHelper::propagate($this, $attributeRules);
439
        }
440
441
        $this->rules = $rules;
442
    }
443
444
    public function afterInitAttribute(object $object, int $target): void
445
    {
446
        if ($this->rules === null) {
447
            return;
448
        }
449
450
        foreach ($this->rules as $rules) {
451
            foreach ((is_iterable($rules) ? $rules : [$rules]) as $rule) {
452
                if ($rule instanceof AfterInitAttributeEventInterface) {
453
                    $rule->afterInitAttribute($object, $target);
454
                }
455
            }
456
        }
457
    }
458
459
    #[ArrayShape([
460
        'requirePropertyPath' => 'bool',
461
        'noRulesWithNoObjectMessage' => 'array',
462
        'incorrectDataSetTypeMessage' => 'array',
463
        'incorrectInputMessage' => 'array',
464
        'noPropertyPathMessage' => 'array',
465
        'skipOnEmpty' => 'bool',
466
        'skipOnError' => 'bool',
467
        'rules' => 'array|null',
468
    ])]
469
    public function getOptions(): array
470
    {
471
        return [
472
            'noRulesWithNoObjectMessage' => [
473
                'template' => $this->noRulesWithNoObjectMessage,
474
                'parameters' => [],
475
            ],
476
            'incorrectDataSetTypeMessage' => [
477
                'template' => $this->incorrectDataSetTypeMessage,
478
                'parameters' => [],
479
            ],
480
            'incorrectInputMessage' => [
481
                'template' => $this->incorrectInputMessage,
482
                'parameters' => [],
483
            ],
484
            'noPropertyPathMessage' => [
485
                'template' => $this->getNoPropertyPathMessage(),
486
                'parameters' => [],
487
            ],
488
            'requirePropertyPath' => $this->isPropertyPathRequired(),
489
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
490
            'skipOnError' => $this->skipOnError,
491
            'rules' => $this->rules === null ? null : RulesDumper::asArray($this->rules),
492
        ];
493
    }
494
495
    public function getHandler(): string
496
    {
497
        return NestedHandler::class;
498
    }
499
}
500