Passed
Push — master ( fdabae...ac5352 )
by Sergei
15:30 queued 13:06
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 43
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 43
ccs 3
cts 3
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
    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 22
    public function __construct(
50
        /**
51
         * Rules for validate value that can be described by:
52
         * - object that implement {@see RulesProviderInterface};
53
         * - name of class from whose attributes their will be derived;
54
         * - array or object implementing the `Traversable` interface that contain {@see RuleInterface} implementations
55
         *   or closures.
56
         *
57
         * `$rules` can be null if validatable value is object. In this case rules will be derived from object via
58
         * `getRules()` method if object implement {@see RulesProviderInterface} or from attributes otherwise.
59
         *
60
         * @var class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null
61
         */
62
        iterable|object|string|null $rules = null,
63
64
        /**
65
         * @var int What visibility levels to use when reading data and rules from validatable object.
66
         */
67
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
68
69
        /**
70
         * @var int What visibility levels to use when reading rules from the class specified in {@see $rules}
71
         * attribute.
72
         */
73
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
74
        private bool $requirePropertyPath = false,
75
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
76
        private bool $normalizeRules = true,
77
        private bool $skipOnEmpty = false,
78
79
        /**
80
         * @var callable
81
         */
82
        private $skipOnEmptyCallback = null,
83
        private bool $skipOnError = false,
84
85
        /**
86
         * @var Closure(mixed, ValidationContext):bool|null
87
         */
88
        private ?Closure $when = null,
89
    ) {
90 22
        $this->initSkipOnEmptyProperties($skipOnEmpty, $skipOnEmptyCallback);
91 22
        $this->rules = $this->prepareRules($rules);
92
    }
93
94
    /**
95
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
96
     */
97 37
    public function getRules(): ?iterable
98
    {
99 37
        return $this->rules;
100
    }
101
102 7
    public function getPropertyVisibility(): int
103
    {
104 7
        return $this->propertyVisibility;
105
    }
106
107
    /**
108
     * @return bool
109
     */
110 31
    public function getRequirePropertyPath(): bool
111
    {
112 31
        return $this->requirePropertyPath;
113
    }
114
115
    /**
116
     * @return string
117
     */
118 8
    public function getNoPropertyPathMessage(): string
119
    {
120 8
        return $this->noPropertyPathMessage;
121
    }
122
123
    /**
124
     * @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...
125
     */
126 22
    private function prepareRules(iterable|object|string|null $source): ?iterable
127
    {
128 22
        if ($source === null) {
129 16
            return null;
130
        }
131
132 6
        if ($source instanceof RulesProviderInterface) {
133 1
            $rules = $source->getRules();
134 1
            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...
135
        }
136
137 5
        $isTraversable = $source instanceof Traversable;
138
139 5
        if (!$isTraversable && !is_array($source)) {
140 2
            $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

140
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $source, $this->rulesPropertyVisibility))->getRules();
Loading history...
141 2
            $this->assertRulesNotEmpty($rules);
142 2
            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...
143
        }
144
145
        /** @psalm-suppress InvalidArgument Psalm don't see $isTraversable above. */
146 3
        $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

146
        $rules = $isTraversable ? iterator_to_array(/** @scrutinizer ignore-type */ $source) : $source;
Loading history...
147 3
        $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

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