Passed
Pull Request — master (#364)
by
unknown
03:03
created

Nested::getIncorrectInputMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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\WhenInterface;
27
28
use function array_pop;
29
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...
30
use function implode;
31
use function is_array;
32
use function is_int;
33
use function is_string;
34
use function ltrim;
35
use function rtrim;
36
use function sprintf;
37
38
/**
39
 * Can be used for validation of nested structures.
40
 */
41
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
42
final class Nested implements
43
    SerializableRuleInterface,
44
    SkipOnErrorInterface,
45
    WhenInterface,
46
    SkipOnEmptyInterface,
47
    PropagateOptionsInterface
48
{
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
    /**
62
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|object|RulesProviderInterface|null $rules
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[]>|object|RulesProviderInterface|null.
Loading history...
63
     *
64
     * Rules for validate value that can be described by:
65
     * - object that implement {@see RulesProviderInterface};
66
     * - name of class from whose attributes their will be derived;
67
     * - array or object implementing the `Traversable` interface that contain {@see RuleInterface} implementations
68
     *   or closures.
69
     *
70
     * `$rules` can be null if validatable value is object. In this case rules will be derived from object via
71
     * `getRules()` method if object implement {@see RulesProviderInterface} or from attributes otherwise.
72
     */
73 23
    public function __construct(
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 string $noRulesWithNoObjectMessage = 'Nested rule without rules can be used for objects only.',
90
        private string $incorrectDataSetTypeMessage = 'An object data set data can only have an array or an object ' .
91
        'type.',
92
        private string $incorrectInputMessage = 'The value must have an array or an object type.',
93
        private bool $requirePropertyPath = false,
94
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
95
        private bool $normalizeRules = true,
96
        private bool $propagateOptions = false,
97
98
        /**
99
         * @var bool|callable|null
100
         */
101
        private $skipOnEmpty = null,
102
        private bool $skipOnError = false,
103
104
        /**
105
         * @var Closure(mixed, ValidationContext):bool|null
106
         */
107
        private ?Closure $when = null,
108
    ) {
109 23
        $this->prepareRules($rules);
110
    }
111
112 2
    public function getName(): string
113
    {
114 2
        return 'nested';
115
    }
116
117
    /**
118
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
119
     */
120 44
    public function getRules(): ?iterable
121
    {
122 44
        return $this->rules;
123
    }
124
125 9
    public function getPropertyVisibility(): int
126
    {
127 9
        return $this->propertyVisibility;
128
    }
129
130 3
    public function getNoRulesWithNoObjectMessage(): string
131
    {
132 3
        return $this->noRulesWithNoObjectMessage;
133
    }
134
135 1
    public function getIncorrectDataSetTypeMessage(): string
136
    {
137 1
        return $this->incorrectDataSetTypeMessage;
138
    }
139
140 2
    public function getIncorrectInputMessage(): string
141
    {
142 2
        return $this->incorrectInputMessage;
143
    }
144
145 37
    public function getRequirePropertyPath(): bool
146
    {
147 37
        return $this->requirePropertyPath;
148
    }
149
150 10
    public function getNoPropertyPathMessage(): string
151
    {
152 10
        return $this->noPropertyPathMessage;
153
    }
154
155
    /**
156
     * @param class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|object|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[]>|object|RulesProviderInterface|null.
Loading history...
157
     */
158 23
    private function prepareRules(iterable|object|string|null $source): void
159
    {
160 23
        if ($source === null) {
161 14
            $this->rules = null;
162
163 14
            return;
164
        }
165
166 9
        if ($source instanceof RulesProviderInterface) {
167 1
            $rules = $source->getRules();
168 8
        } elseif (!$source instanceof Traversable && !is_array($source)) {
169 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

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