Passed
Pull Request — master (#550)
by
unknown
04:08 queued 01:12
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

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