Test Failed
Pull Request — master (#297)
by Sergei
02:26
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 41
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 41
ccs 12
cts 12
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\BeforeValidationInterface;
15
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait;
16
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
17
use Yiisoft\Validator\RuleInterface;
18
use Yiisoft\Validator\RulesDumper;
19
use Yiisoft\Validator\RulesProvider\AttributesRulesProvider;
20
use Yiisoft\Validator\RulesProviderInterface;
21
use Yiisoft\Validator\SerializableRuleInterface;
22
use Yiisoft\Validator\ValidationContext;
23
24
use function array_pop;
25
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...
26
use function implode;
27
use function is_array;
28
use function ltrim;
29
use function rtrim;
30
use function sprintf;
31
32
/**
33
 * Can be used for validation of nested structures.
34
 */
35
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
36
final class Nested implements SerializableRuleInterface, BeforeValidationInterface
37
{
38
    use BeforeValidationTrait;
39
    use RuleNameTrait;
40
41 6
    private const SEPARATOR = '.';
42
    private const EACH_SHORTCUT = '*';
43
44
    /**
45
     * @var iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
46
     */
47
    private ?iterable $rules = null;
48
49
    public function __construct(
50
        /**
51
         * Null available only for objects.
52
         *
53
         * @var class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null
54
         */
55
        iterable|object|string|null $rules = null,
56
57
        /**
58
         * Use on parse data and rules from object value when {@see $rules} is null.
59
         *
60 6
         * @var int
61
         */
62 6
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
63 6
64 1
        /**
65
         * This options use on parse rules from class defined in {@see $rules}.
66
         *
67 5
         * @var int
68 1
         */
69 1
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
70
71
        private bool $requirePropertyPath = false,
72 4
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
73
        private bool $normalizeRules = true,
74 4
        private bool $skipOnEmpty = false,
75 4
76
        /**
77
         * @var callable
78
         */
79
        private $skipOnEmptyCallback = null,
80
81
        private bool $skipOnError = false,
82 27
83
        /**
84 27
         * @var Closure(mixed, ValidationContext):bool|null
85
         */
86
        private ?Closure $when = null,
87
    ) {
88
        $this->initSkipOnEmptyProperties($skipOnEmpty, $skipOnEmptyCallback);
89
        $this->rules = $this->prepareRules($rules);
90 27
    }
91
92 27
    /**
93
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
94
     */
95
    public function getRules(): ?iterable
96
    {
97
        return $this->rules;
98 7
    }
99
100 7
    public function getPropertyVisibility(): int
101
    {
102
        return $this->propertyVisibility;
103 5
    }
104
105 5
    /**
106
     * @return bool
107 5
     */
108 5
    public function getRequirePropertyPath(): bool
109
    {
110
        return $this->requirePropertyPath;
111
    }
112
113
    /**
114 4
     * @return string
115
     */
116
    public function getNoPropertyPathMessage(): string
117 4
    {
118 4
        return $this->noPropertyPathMessage;
119 4
    }
120 4
121
    /**
122 4
     * @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...
123 4
     */
124 1
    private function prepareRules(iterable|object|string|null $source): ?iterable
125
    {
126
        if ($source === null) {
127 3
            return null;
128 3
        }
129
130
        if ($source instanceof RulesProviderInterface) {
131
            $rules = $source->getRules();
132 3
            return $this->normalizeRules ? $this->normalizeRules($rules) : $rules;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->normalizeR...eRules($rules) : $rules could return the type array which is incompatible with the type-hinted return iterable|null. Consider adding an additional type-check to rule them out.
Loading history...
133 3
        }
134
135
        $isTraversable = $source instanceof Traversable;
136
137
        if (!$isTraversable && !is_array($source)) {
138
            $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

138
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $source, $this->rulesPropertyVisibility))->getRules();
Loading history...
139
            $this->assertRulesNotEmpty($rules);
140
            return $rules;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $rules returns the type array which is incompatible with the type-hinted return iterable|null.
Loading history...
141
        }
142
143
        /** @psalm-suppress InvalidArgument Psalm don't see $isTraversable above. */
144
        $rules = $isTraversable ? iterator_to_array($source) : $source;
0 ignored issues
show
Bug introduced by
It seems like $source can also be of type array; however, parameter $iterator of iterator_to_array() does only seem to accept Traversable, 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

144
        $rules = $isTraversable ? iterator_to_array(/** @scrutinizer ignore-type */ $source) : $source;
Loading history...
145
        $this->assertRulesNotEmpty($rules);
0 ignored issues
show
Bug introduced by
It seems like $rules can also be of type Traversable; however, parameter $rules of Yiisoft\Validator\Rule\N...::assertRulesNotEmpty() does only seem to accept array, 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
        $this->assertRulesNotEmpty(/** @scrutinizer ignore-type */ $rules);
Loading history...
146
147
        if (self::checkRules($rules)) {
148
            $message = sprintf('Each rule should be an instance of %s.', RuleInterface::class);
149
            throw new InvalidArgumentException($message);
150
        }
151
152
        return $this->normalizeRules ? $this->normalizeRules($rules) : $rules;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->normalizeR...eRules($rules) : $rules returns the type array which is incompatible with the type-hinted return iterable|null.
Loading history...
153 3
    }
154
155
    private static function checkRules($rules): bool
156
    {
157 3
        return array_reduce(
158 3
            $rules,
159
            function (bool $carry, $rule) {
160
                return $carry || (is_array($rule) ? self::checkRules($rule) : !$rule instanceof RuleInterface);
161
            },
162 3
            false
163
        );
164
    }
165 4
166
    private function normalizeRules(iterable $sourceRules): array
167
    {
168
        $rules = $sourceRules instanceof Traversable ? iterator_to_array($sourceRules) : $sourceRules;
169
        while (true) {
170
            $breakWhile = true;
171
            $rulesMap = [];
172
173
            foreach ($rules as $valuePath => $rule) {
174
                if ($valuePath === self::EACH_SHORTCUT) {
175 4
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
176
                }
177 4
178
                $parts = StringHelper::parsePath(
179 4
                    (string) $valuePath,
180 4
                    delimiter: self::EACH_SHORTCUT,
181 4
                    preserveDelimiterEscaping: true
182
                );
183
                if (count($parts) === 1) {
184
                    continue;
185 11
                }
186
187 11
                $breakWhile = false;
188
189
                $lastValuePath = array_pop($parts);
190
                $lastValuePath = ltrim($lastValuePath, '.');
191
                $lastValuePath = str_replace('\\' . self::EACH_SHORTCUT, self::EACH_SHORTCUT, $lastValuePath);
192
193
                $remainingValuePath = implode(self::EACH_SHORTCUT, $parts);
194
                $remainingValuePath = rtrim($remainingValuePath, self::SEPARATOR);
195
196
                if (!isset($rulesMap[$remainingValuePath])) {
197
                    $rulesMap[$remainingValuePath] = [];
198
                }
199
200
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
201
                unset($rules[$valuePath]);
202
            }
203
204
            foreach ($rulesMap as $valuePath => $nestedRules) {
205
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
206
            }
207
208
            if ($breakWhile === true) {
209
                break;
210
            }
211
        }
212
213
        return $rules;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $rules could return the type iterable which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
214
    }
215
216
    #[ArrayShape([
217
        'requirePropertyPath' => 'bool',
218
        'noPropertyPathMessage' => 'array',
219
        'skipOnEmpty' => 'bool',
220
        'skipOnError' => 'bool',
221
        'rules' => 'array|null',
222
    ])]
223
    public function getOptions(): array
224
    {
225
        return [
226
            'requirePropertyPath' => $this->getRequirePropertyPath(),
227
            'noPropertyPathMessage' => [
228
                'message' => $this->getNoPropertyPathMessage(),
229
            ],
230
            'skipOnEmpty' => $this->skipOnEmpty,
231
            'skipOnError' => $this->skipOnError,
232
            'rules' => $this->rules === null ? null : (new RulesDumper())->asArray($this->rules),
233
        ];
234
    }
235
236
    public function getHandlerClassName(): string
237
    {
238
        return NestedHandler::class;
239
    }
240
241
    private function assertRulesNotEmpty(array $rules): void
242
    {
243
        if (empty($rules)) {
244
            throw new InvalidArgumentException('Rules must not be empty.');
245
        }
246
    }
247
}
248