Passed
Pull Request — master (#331)
by Sergei
02:46
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 45
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 45
ccs 2
cts 2
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\RuleNameTrait;
16
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
17
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
18
use Yiisoft\Validator\Rule\Trait\WhenTrait;
19
use Yiisoft\Validator\RuleInterface;
20
use Yiisoft\Validator\RulesDumper;
21
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
22
use Yiisoft\Validator\RulesProviderInterface;
23
use Yiisoft\Validator\SerializableRuleInterface;
24
use Yiisoft\Validator\SkipOnEmptyInterface;
25
use Yiisoft\Validator\SkipOnErrorInterface;
26
use Yiisoft\Validator\ValidationContext;
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 ltrim;
34
use function rtrim;
35
use function sprintf;
36
37
/**
38
 * Can be used for validation of nested structures.
39
 */
40
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
41
final class Nested implements
42
    SerializableRuleInterface,
43
    SkipOnErrorInterface,
44
    WhenInterface,
45
    SkipOnEmptyInterface,
46
    PropagateOptionsInterface
47
{
48
    use RuleNameTrait;
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
    private ?iterable $rules;
60
61 23
    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
        private ?Closure $when = null,
104
    ) {
105 23
        $this->prepareRules($rules);
106
    }
107
108
    /**
109
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
110
     */
111 39
    public function getRules(): ?iterable
112
    {
113 39
        return $this->rules;
114
    }
115
116 8
    public function getPropertyVisibility(): int
117
    {
118 8
        return $this->propertyVisibility;
119
    }
120
121 33
    public function getRequirePropertyPath(): bool
122
    {
123 33
        return $this->requirePropertyPath;
124
    }
125
126 9
    public function getNoPropertyPathMessage(): string
127
    {
128 9
        return $this->noPropertyPathMessage;
129
    }
130
131
    /**
132
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|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[]>|RulesProviderInterface|null.
Loading history...
133
     */
134 23
    private function prepareRules(iterable|object|string|null $source): void
135
    {
136 23
        if ($source === null) {
137 14
            $this->rules = null;
138
139 14
            return;
140
        }
141
142 9
        if ($source instanceof RulesProviderInterface) {
143 1
            $rules = $source->getRules();
144 8
        } elseif (!$source instanceof Traversable && !is_array($source)) {
145 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

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