Passed
Pull Request — master (#297)
by Sergei
02:43
created

Nested::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 32
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 32
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 9
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
         * 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 when {@see $rules} is null.
59
         *
60
         * @var int
61
         */
62
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
63
        private bool $requirePropertyPath = false,
64
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
65
        private bool $normalizeRules = true,
66
        private bool $skipOnEmpty = false,
67
68
        /**
69
         * @var callable
70
         */
71
        private $skipOnEmptyCallback = null,
72
        private bool $skipOnError = false,
73
74
        /**
75
         * @var Closure(mixed, ValidationContext):bool|null
76
         */
77
        private ?Closure $when = null,
78
    ) {
79 22
        $this->initSkipOnEmptyProperties($skipOnEmpty, $skipOnEmptyCallback);
80 22
        $this->rules = $this->prepareRules($rules);
81
    }
82
83
    /**
84
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
85
     */
86 37
    public function getRules(): ?iterable
87
    {
88 37
        return $this->rules;
89
    }
90
91 7
    public function getPropertyVisibility(): int
92
    {
93 7
        return $this->propertyVisibility;
94
    }
95
96
    /**
97
     * @return bool
98
     */
99 31
    public function getRequirePropertyPath(): bool
100
    {
101 31
        return $this->requirePropertyPath;
102
    }
103
104
    /**
105
     * @return string
106
     */
107 8
    public function getNoPropertyPathMessage(): string
108
    {
109 8
        return $this->noPropertyPathMessage;
110
    }
111
112
    /**
113
     * @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...
114
     */
115 22
    private function prepareRules(iterable|object|string|null $source): ?iterable
116
    {
117 22
        if ($source === null) {
118 16
            return null;
119
        }
120
121 6
        if ($source instanceof RulesProviderInterface) {
122 1
            $rules = $source->getRules();
123 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...
124
        }
125
126 5
        $isTraversable = $source instanceof Traversable;
127
128 5
        if (!$isTraversable && !is_array($source)) {
129 2
            $rules = (new AttributesRulesProvider($source, $this->propertyVisibility))->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

129
            $rules = (new AttributesRulesProvider(/** @scrutinizer ignore-type */ $source, $this->propertyVisibility))->getRules();
Loading history...
130 2
            $this->assertRulesNotEmpty($rules);
131 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...
132
        }
133
134
        /** @psalm-suppress InvalidArgument Psalm don't see $isTraversable above. */
135 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

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

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