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

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