Passed
Push — master ( 746440...f48ff6 )
by
unknown
06:04 queued 02:55
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 37
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

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\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\RuleInterface;
19
use Yiisoft\Validator\RulesDumper;
20
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
21
use Yiisoft\Validator\RulesProviderInterface;
22
use Yiisoft\Validator\SerializableRuleInterface;
23
use Yiisoft\Validator\SkipOnEmptyInterface;
24
use Yiisoft\Validator\SkipOnErrorInterface;
25
use Yiisoft\Validator\Tests\Rule\NestedTest;
26
use Yiisoft\Validator\ValidationContext;
27
use Yiisoft\Validator\ValidatorInterface;
28
use Yiisoft\Validator\WhenInterface;
29
30
use function array_pop;
31
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...
32
use function implode;
33
use function is_array;
34
use function ltrim;
35
use function rtrim;
36
use function sprintf;
37
38
/**
39
 * Can be used for validation of nested structures.
40
 *
41
 * @psalm-import-type RulesType from ValidatorInterface
42
 */
43
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
44
final class Nested implements
45
    SerializableRuleInterface,
46
    SkipOnErrorInterface,
47
    WhenInterface,
48
    SkipOnEmptyInterface,
49
    PropagateOptionsInterface
50
{
51
    use SkipOnEmptyTrait;
52
    use SkipOnErrorTrait;
53
    use WhenTrait;
54
55
    private const SEPARATOR = '.';
56
    private const EACH_SHORTCUT = '*';
57
58
    /**
59
     * @var iterable<iterable<RuleInterface>|RuleInterface>|null
60
     */
61
    private iterable|null $rules;
62
63
    /**
64
     * @param iterable|object|string|null $rules Rules for validate value that can be described by:
65
     *
66
     * - object that implement {@see RulesProviderInterface};
67
     * - name of class from whose attributes their will be derived;
68
     * - array or object implementing the `Traversable` interface that contain {@see RuleInterface} implementations
69
     *   or closures.
70
     *
71
     * `$rules` can be null if validatable value is object. In this case rules will be derived from object via
72
     * `getRules()` method if object implement {@see RulesProviderInterface} or from attributes otherwise.
73
     * @psalm-param RulesType $rules
74
     */
75 23
    public function __construct(
76
        iterable|object|string|null $rules = null,
77
78
        /**
79
         * @var int What visibility levels to use when reading data and rules from validated object.
80
         */
81
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE
82
        | ReflectionProperty::IS_PROTECTED
83
        | ReflectionProperty::IS_PUBLIC,
84
        /**
85
         * @var int What visibility levels to use when reading rules from the class specified in {@see $rules}
86
         * attribute.
87
         */
88
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
89
        | ReflectionProperty::IS_PROTECTED
90
        | ReflectionProperty::IS_PUBLIC,
91
        private string $noRulesWithNoObjectMessage = 'Nested rule without rules can be used for objects only.',
92
        private string $incorrectDataSetTypeMessage = 'An object data set data can only have an array or an object ' .
93
        'type.',
94
        private string $incorrectInputMessage = 'The value must have an array or an object type.',
95
        private bool $requirePropertyPath = false,
96
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
97
        private bool $normalizeRules = true,
98
        private bool $propagateOptions = false,
99
100
        /**
101
         * @var bool|callable|null
102
         */
103
        private $skipOnEmpty = null,
104
        private bool $skipOnError = false,
105
106
        /**
107
         * @var Closure(mixed, ValidationContext):bool|null
108
         */
109
        private ?Closure $when = null,
110
    ) {
111 23
        $this->prepareRules($rules);
112
    }
113
114 2
    public function getName(): string
115
    {
116 2
        return 'nested';
117
    }
118
119
    /**
120
     * @return iterable<iterable<RuleInterface>|RuleInterface>|null
121
     */
122 45
    public function getRules(): iterable|null
123
    {
124 45
        return $this->rules;
125
    }
126
127 9
    public function getPropertyVisibility(): int
128
    {
129 9
        return $this->propertyVisibility;
130
    }
131
132 3
    public function getNoRulesWithNoObjectMessage(): string
133
    {
134 3
        return $this->noRulesWithNoObjectMessage;
135
    }
136
137 1
    public function getIncorrectDataSetTypeMessage(): string
138
    {
139 1
        return $this->incorrectDataSetTypeMessage;
140
    }
141
142 2
    public function getIncorrectInputMessage(): string
143
    {
144 2
        return $this->incorrectInputMessage;
145
    }
146
147 38
    public function getRequirePropertyPath(): bool
148
    {
149 38
        return $this->requirePropertyPath;
150
    }
151
152 10
    public function getNoPropertyPathMessage(): string
153
    {
154 10
        return $this->noPropertyPathMessage;
155
    }
156
157
    /**
158
     * @psalm-param RulesType $source
159
     */
160 23
    private function prepareRules(iterable|object|string|null $source): void
161
    {
162 23
        if ($source === null) {
163 14
            $this->rules = null;
164
165 14
            return;
166
        }
167
168 9
        if ($source instanceof RulesProviderInterface) {
169 1
            $rules = $source->getRules();
170 8
        } elseif (!$source instanceof Traversable && !is_array($source)) {
171 4
            $rules = (new AttributesRulesProvider($source, $this->rulesPropertyVisibility))->getRules();
0 ignored issues
show
Bug introduced by
It seems like $source can also be of type iterable; however, parameter $source of Yiisoft\Validator\RulesP...Provider::__construct() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

171
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $source, $this->rulesPropertyVisibility))->getRules();
Loading history...
172
        } else {
173 4
            $rules = $source;
174
        }
175
176 9
        self::ensureArrayHasRules($rules);
177 8
        $this->rules = $rules;
178
179 8
        if ($this->normalizeRules) {
180 8
            $this->normalizeRules();
181
        }
182
183 7
        if ($this->propagateOptions) {
184 1
            $this->propagateOptions();
185
        }
186
    }
187
188
    /**
189
     * @psalm-assert iterable<RuleInterface> $rules
190
     */
191 9
    private static function ensureArrayHasRules(iterable &$rules): void
192
    {
193 9
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
194
195 9
        foreach ($rules as &$rule) {
196 8
            if (is_iterable($rule)) {
197 6
                self::ensureArrayHasRules($rule);
198 6
                continue;
199
            }
200 8
            if (!$rule instanceof RuleInterface) {
201 1
                $message = sprintf(
202
                    'Each rule should be an instance of %s, %s given.',
203
                    RuleInterface::class,
204 1
                    get_debug_type($rule)
205
                );
206 1
                throw new InvalidArgumentException($message);
207
            }
208
        }
209
    }
210
211 8
    private function normalizeRules(): void
212
    {
213
        /** @var RuleInterface[] $rules Conversion to array is done in {@see ensureArrayHasRules()}. */
214 8
        $rules = $this->rules;
215 8
        while (true) {
216 8
            $breakWhile = true;
217 8
            $rulesMap = [];
218
219 8
            foreach ($rules as $valuePath => $rule) {
220 7
                if ($valuePath === self::EACH_SHORTCUT) {
221 1
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
222
                }
223
224 6
                $parts = StringHelper::parsePath(
225 6
                    (string) $valuePath,
226
                    delimiter: self::EACH_SHORTCUT,
227
                    preserveDelimiterEscaping: true
228
                );
229 6
                if (count($parts) === 1) {
230 6
                    continue;
231
                }
232
233
                /**
234
                 * Might be a bug of XDebug, because these lines are covered by tests.
235
                 *
236
                 * @see NestedTest::dataWithOtherNestedAndEach() for test cases prefixed with "withShortcut".
237
                 */
238
                // @codeCoverageIgnoreStart
239
                $breakWhile = false;
240
241
                $lastValuePath = array_pop($parts);
242
                $lastValuePath = ltrim($lastValuePath, '.');
243
                $lastValuePath = str_replace('\\' . self::EACH_SHORTCUT, self::EACH_SHORTCUT, $lastValuePath);
244
245
                $remainingValuePath = implode(self::EACH_SHORTCUT, $parts);
246
                $remainingValuePath = rtrim($remainingValuePath, self::SEPARATOR);
247
248
                if (!isset($rulesMap[$remainingValuePath])) {
249
                    $rulesMap[$remainingValuePath] = [];
250
                }
251
252
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
253
                unset($rules[$valuePath]);
254
                // @codeCoverageIgnoreEnd
255
            }
256
257 7
            foreach ($rulesMap as $valuePath => $nestedRules) {
258
                /**
259
                 * Might be a bug of XDebug, because this line is covered by tests.
260
                 *
261
                 * @see NestedTest::dataWithOtherNestedAndEach() for test cases prefixed with "withShortcut".
262
                 */
263
                // @codeCoverageIgnoreStart
264
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
265
                // @codeCoverageIgnoreEnd
266
            }
267
268 7
            if ($breakWhile === true) {
269 7
                break;
270
            }
271
        }
272
273 7
        $this->rules = $rules;
274
    }
275
276 1
    public function propagateOptions(): void
277
    {
278 1
        $rules = [];
279
        /**
280
         * @psalm-suppress PossiblyNullIterator Rules can't be null at this point because of the order and check with
281
         * early return in {@see prepareRules()}.
282
         *
283
         * @var int|string $attributeRulesIndex Index is either integer or string because of the array conversion in
284
         * {@see ensureArrayHasRules()}.
285
         * @var RuleInterface[] $attributeRules Conversion to array is done in {@see ensureArrayHasRules()}.
286
         */
287 1
        foreach ($this->rules as $attributeRulesIndex => $attributeRules) {
288 1
            foreach ($attributeRules as $attributeRule) {
289 1
                if ($attributeRule instanceof SkipOnEmptyInterface) {
290 1
                    $attributeRule = $attributeRule->skipOnEmpty($this->skipOnEmpty);
291
                }
292 1
                if ($attributeRule instanceof SkipOnErrorInterface) {
293 1
                    $attributeRule = $attributeRule->skipOnError($this->skipOnError);
294
                }
295 1
                if ($attributeRule instanceof WhenInterface) {
296 1
                    $attributeRule = $attributeRule->when($this->when);
297
                }
298
299 1
                $rules[$attributeRulesIndex][] = $attributeRule;
300
301 1
                if ($attributeRule instanceof PropagateOptionsInterface) {
302 1
                    $attributeRule->propagateOptions();
303
                }
304
            }
305
        }
306
307 1
        $this->rules = $rules;
308
    }
309
310 5
    #[ArrayShape([
311
        'requirePropertyPath' => 'bool',
312
        'noPropertyPathMessage' => 'array',
313
        'skipOnEmpty' => 'bool',
314
        'skipOnError' => 'bool',
315
        'rules' => 'array|null',
316
    ])]
317
    public function getOptions(): array
318
    {
319
        return [
320 5
            'noRulesWithNoObjectMessage' => $this->noRulesWithNoObjectMessage,
321 5
            'incorrectDataSetTypeMessage' => $this->incorrectDataSetTypeMessage,
322 5
            'incorrectInputMessage' => $this->incorrectInputMessage,
323 5
            'requirePropertyPath' => $this->getRequirePropertyPath(),
324
            'noPropertyPathMessage' => [
325 5
                'message' => $this->getNoPropertyPathMessage(),
326
            ],
327 5
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
328 5
            'skipOnError' => $this->skipOnError,
329 5
            'rules' => $this->rules === null ? null : (new RulesDumper())->asArray($this->rules),
330
        ];
331
    }
332
333 45
    public function getHandlerClassName(): string
334
    {
335 45
        return NestedHandler::class;
336
    }
337
}
338