Test Failed
Pull Request — master (#364)
by
unknown
02:49
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 45
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 45
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 10
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\ValidationContext;
26
use Yiisoft\Validator\WhenInterface;
27
28
use function array_pop;
29
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...
30
use function implode;
31
use function is_array;
32
use function is_int;
33
use function is_string;
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
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
42
final class Nested implements
43
    SerializableRuleInterface,
44
    SkipOnErrorInterface,
45
    WhenInterface,
46
    SkipOnEmptyInterface,
47
    PropagateOptionsInterface
48
{
49
    use SkipOnEmptyTrait;
50
    use SkipOnErrorTrait;
51
    use WhenTrait;
52
53
    private const SEPARATOR = '.';
54
    private const EACH_SHORTCUT = '*';
55
56
    /**
57
     * @var iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
58
     */
59 23
    private ?iterable $rules;
60
61
    public function __construct(
62
        /**
63
         * Rules for validate value that can be described by:
64
         * - object that implement {@see RulesProviderInterface};
65
         * - name of class from whose attributes their will be derived;
66
         * - array or object implementing the `Traversable` interface that contain {@see RuleInterface} implementations
67
         *   or closures.
68
         *
69
         * `$rules` can be null if validatable value is object. In this case rules will be derived from object via
70
         * `getRules()` method if object implement {@see RulesProviderInterface} or from attributes otherwise.
71
         *
72
         * @var class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null
73
         */
74
        iterable|object|string|null $rules = null,
75
76
        /**
77
         * @var int What visibility levels to use when reading data and rules from validated object.
78
         */
79
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE
80
        | ReflectionProperty::IS_PROTECTED
81
        | ReflectionProperty::IS_PUBLIC,
82
        /**
83
         * @var int What visibility levels to use when reading rules from the class specified in {@see $rules}
84
         * attribute.
85
         */
86
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
87
        | ReflectionProperty::IS_PROTECTED
88
        | ReflectionProperty::IS_PUBLIC,
89
        private bool $requirePropertyPath = false,
90
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
91
        private bool $normalizeRules = true,
92
        private bool $propagateOptions = false,
93
94
        /**
95
         * @var bool|callable|null
96
         */
97
        private $skipOnEmpty = null,
98
        private bool $skipOnError = false,
99
100
        /**
101
         * @var Closure(mixed, ValidationContext):bool|null
102
         */
103 23
        private ?Closure $when = null,
104
    ) {
105
        $this->prepareRules($rules);
106 2
    }
107
108 2
    public function getName(): string
109
    {
110
        return 'nested';
111
    }
112
113
    /**
114 39
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
115
     */
116 39
    public function getRules(): ?iterable
117
    {
118
        return $this->rules;
119 8
    }
120
121 8
    public function getPropertyVisibility(): int
122
    {
123
        return $this->propertyVisibility;
124 33
    }
125
126 33
    public function getRequirePropertyPath(): bool
127
    {
128
        return $this->requirePropertyPath;
129 9
    }
130
131 9
    public function getNoPropertyPathMessage(): string
132
    {
133
        return $this->noPropertyPathMessage;
134
    }
135
136
    /**
137 23
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|object|RulesProviderInterface|null $source
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string|iterable<Cl...sProviderInterface|null at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|object|RulesProviderInterface|null.
Loading history...
138
     */
139 23
    private function prepareRules(iterable|object|string|null $source): void
140 14
    {
141
        if ($source === null) {
142 14
            $this->rules = null;
143
144
            return;
145 9
        }
146 1
147 8
        if ($source instanceof RulesProviderInterface) {
148 4
            $rules = $source->getRules();
149
        } elseif (!$source instanceof Traversable && !is_array($source)) {
150 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

150
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $source, $this->rulesPropertyVisibility))->getRules();
Loading history...
151
        } else {
152
            $rules = $source;
153 9
        }
154 9
155
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
156 8
        self::ensureArrayHasRules($rules);
157
158 8
        /** @var iterable<RuleInterface> $rules */
159 8
        $this->rules = $rules;
160
161
        if ($this->normalizeRules) {
162 7
            $this->normalizeRules();
163 1
        }
164
165
        if ($this->propagateOptions) {
166
            $this->propagateOptions();
167 9
        }
168
    }
169 9
170
    private static function ensureArrayHasRules(iterable &$rules): void
171 9
    {
172 8
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
173 6
174 6
        foreach ($rules as &$rule) {
175
            if (is_iterable($rule)) {
176 8
                self::ensureArrayHasRules($rule);
177 1
                continue;
178
            }
179
            if (!$rule instanceof RuleInterface) {
180 1
                $message = sprintf(
181
                    'Each rule should be an instance of %s, %s given.',
182 1
                    RuleInterface::class,
183
                    get_debug_type($rule)
184
                );
185
                throw new InvalidArgumentException($message);
186
            }
187 8
        }
188
    }
189
190 8
    private function normalizeRules(): void
191
    {
192 8
        if ($this->rules === null) {
193 8
            return;
194 8
        }
195
196 8
        /** @var iterable<RuleInterface> $rules */
197 7
        $rules = $this->rules;
198 1
        if ($rules instanceof Traversable) {
199
            $rules = iterator_to_array($rules);
200
        }
201 6
202 6
        while (true) {
203
            $breakWhile = true;
204
            $rulesMap = [];
205
206 6
            /** @var mixed $valuePath */
207 6
            foreach ($rules as $valuePath => $rule) {
208
                if (is_int($valuePath)) {
209
                    $valuePath = (string) $valuePath;
210
                } elseif (!is_string($valuePath)) {
211
                    $message = sprintf(
212
                        'A value path can only have an integer or a string type. %s given',
213
                        get_debug_type($valuePath),
214
                    );
215
216
                    throw new InvalidArgumentException($message);
217
                }
218
219
                if ($valuePath === self::EACH_SHORTCUT) {
220
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
221
                }
222
223
                $parts = StringHelper::parsePath(
224
                    $valuePath,
225
                    delimiter: self::EACH_SHORTCUT,
226
                    preserveDelimiterEscaping: true
227 7
                );
228
                if (count($parts) === 1) {
229
                    continue;
230
                }
231 7
232 7
                $breakWhile = false;
233
234
                $lastValuePath = array_pop($parts);
235
                $lastValuePath = ltrim($lastValuePath, '.');
236 7
                $lastValuePath = str_replace('\\' . self::EACH_SHORTCUT, self::EACH_SHORTCUT, $lastValuePath);
237
238
                $remainingValuePath = implode(self::EACH_SHORTCUT, $parts);
239 1
                $remainingValuePath = rtrim($remainingValuePath, self::SEPARATOR);
240
241 1
                if (!isset($rulesMap[$remainingValuePath])) {
242 1
                    $rulesMap[$remainingValuePath] = [];
243 1
                }
244 1
245 1
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
246
                unset($rules[$valuePath]);
247 1
            }
248 1
249
            foreach ($rulesMap as $valuePath => $nestedRules) {
250 1
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
251 1
            }
252
253
            if ($breakWhile === true) {
254 1
                break;
255
            }
256 1
        }
257 1
258
        $this->rules = $rules;
259
    }
260
261
    public function propagateOptions(): void
262 1
    {
263
        if ($this->rules === null) {
264
            return;
265 5
        }
266
267
        $rules = [];
268
        /** @var iterable<RuleInterface> $attributeRules */
269
        foreach ($this->rules as $attributeRulesIndex => $attributeRules) {
270
            if (!is_int($attributeRulesIndex) && !is_string($attributeRulesIndex)) {
271
                $message = sprintf(
272
                    'A value path can only have an integer or a string type. %s given',
273
                    get_debug_type($attributeRulesIndex),
274
                );
275 5
276
                throw new InvalidArgumentException($message);
277 5
            }
278
279 5
            foreach ($attributeRules as $attributeRule) {
280 5
                if ($attributeRule instanceof SkipOnEmptyInterface) {
281 5
                    $attributeRule = $attributeRule->skipOnEmpty($this->skipOnEmpty);
282
                }
283
                if ($attributeRule instanceof SkipOnErrorInterface) {
284
                    $attributeRule = $attributeRule->skipOnError($this->skipOnError);
285 39
                }
286
                if ($attributeRule instanceof WhenInterface) {
287 39
                    $attributeRule = $attributeRule->when($this->when);
288
                }
289
290
                $rules[$attributeRulesIndex][] = $attributeRule;
291
292
                if ($attributeRule instanceof PropagateOptionsInterface) {
293
                    $attributeRule->propagateOptions();
294
                }
295
            }
296
        }
297
298
        $this->rules = $rules;
299
    }
300
301
    #[ArrayShape([
302
        'requirePropertyPath' => 'bool',
303
        'noPropertyPathMessage' => 'array',
304
        'skipOnEmpty' => 'bool',
305
        'skipOnError' => 'bool',
306
        'rules' => 'array|null',
307
    ])]
308
    public function getOptions(): array
309
    {
310
        return [
311
            'requirePropertyPath' => $this->getRequirePropertyPath(),
312
            'noPropertyPathMessage' => [
313
                'message' => $this->getNoPropertyPathMessage(),
314
            ],
315
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
316
            'skipOnError' => $this->skipOnError,
317
            'rules' => $this->rules === null ? null : (new RulesDumper())->asArray($this->rules),
318
        ];
319
    }
320
321
    public function getHandlerClassName(): string
322
    {
323
        return NestedHandler::class;
324
    }
325
}
326