Test Failed
Pull Request — master (#279)
by Alexander
05:24 queued 02:19
created

Nested::normalizeRules()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 45
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 45
ccs 5
cts 5
cp 1
rs 8.4444
cc 8
nc 18
nop 0
crap 8
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 Traversable;
12
use Yiisoft\Arrays\ArrayHelper;
13
use Yiisoft\Validator\BeforeValidationInterface;
14
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait;
15
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
16
use Yiisoft\Validator\RuleInterface;
17
use Yiisoft\Validator\RulesDumper;
18
use Yiisoft\Validator\SerializableRuleInterface;
19
use Yiisoft\Validator\ValidationContext;
20
21
use function array_pop;
22
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...
23
use function implode;
24
use function is_array;
25
use function ltrim;
26
use function rtrim;
27
use function sprintf;
28
29
/**
30
 * Can be used for validation of nested structures.
31
 */
32 4
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
33
final class Nested implements SerializableRuleInterface, BeforeValidationInterface
34
{
35
    use BeforeValidationTrait;
36
    use RuleNameTrait;
37
38
    private const SEPARATOR = '.';
39
    private const EACH_SHORTCUT = '*';
40
41
    public function __construct(
42
        /**
43
         * @var iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
44
         */
45
        private iterable $rules = [],
46 4
        private bool $requirePropertyPath = false,
47 4
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
48 1
        private bool $normalizeRules = true,
49
        private bool $skipOnEmpty = false,
50
        private bool $skipOnError = false,
51 3
        /**
52 1
         * @var Closure(mixed, ValidationContext):bool|null
53 1
         */
54
        private ?Closure $when = null,
55
    ) {
56 2
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
57
        if (empty($rules)) {
58
            throw new InvalidArgumentException('Rules must not be empty.');
59
        }
60
61
        if (self::checkRules($rules)) {
62 16
            $message = sprintf('Each rule should be an instance of %s.', RuleInterface::class);
63
            throw new InvalidArgumentException($message);
64 16
        }
65
66
        $this->rules = $rules;
67
68
        if ($this->normalizeRules === true) {
69
            $this->normalizeRules();
70 20
        }
71
    }
72 20
73
    /**
74
     * @return iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
75
     */
76
    public function getRules(): iterable
77
    {
78 7
        return $this->rules;
79
    }
80 7
81
    /**
82
     * @return bool
83 3
     */
84
    public function getRequirePropertyPath(): bool
85 3
    {
86
        return $this->requirePropertyPath;
87 3
    }
88 3
89
    /**
90
     * @return string
91
     */
92
    public function getNoPropertyPathMessage(): string
93
    {
94 4
        return $this->noPropertyPathMessage;
95
    }
96
97
    private static function checkRules($rules): bool
98
    {
99
        return array_reduce(
100
            $rules,
101
            function (bool $carry, $rule) {
102
                return $carry || (is_array($rule) ? self::checkRules($rule) : !$rule instanceof RuleInterface);
103
            },
104 4
            false
105
        );
106 4
    }
107
108 4
    private function normalizeRules(): void
109 4
    {
110 4
        /** @var iterable $rules */
111
        $rules = $this->getRules();
112
        while (true) {
113
            $breakWhile = true;
114 6
            $rulesMap = [];
115
116 6
            foreach ($rules as $valuePath => $rule) {
117
                if ($valuePath === self::EACH_SHORTCUT) {
118
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
119
                }
120
121
                $parts = ArrayHelper::parsePath((string) $valuePath, self::EACH_SHORTCUT, false);
0 ignored issues
show
Unused Code introduced by
The call to Yiisoft\Arrays\ArrayHelper::parsePath() has too many arguments starting with false. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

121
                /** @scrutinizer ignore-call */ 
122
                $parts = ArrayHelper::parsePath((string) $valuePath, self::EACH_SHORTCUT, false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
122
                if (count($parts) === 1) {
123
                    continue;
124
                }
125
126
                $breakWhile = false;
127
128
                $lastValuePath = array_pop($parts);
129
                $lastValuePath = ltrim($lastValuePath, '.');
130
                $lastValuePath = str_replace('\\' . self::EACH_SHORTCUT, self::EACH_SHORTCUT, $lastValuePath);
131
132
                $remainingValuePath = implode(self::EACH_SHORTCUT, $parts);
133
                $remainingValuePath = rtrim($remainingValuePath, self::SEPARATOR);
134
135
                if (!isset($rulesMap[$remainingValuePath])) {
136
                    $rulesMap[$remainingValuePath] = [];
137
                }
138
139
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
140
                unset($rules[$valuePath]);
141
            }
142
143
            foreach ($rulesMap as $valuePath => $nestedRules) {
144
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
145
            }
146
147
            if ($breakWhile === true) {
148
                break;
149
            }
150
        }
151
152
        $this->rules = $rules;
153
    }
154
155
    #[ArrayShape([
156
        'requirePropertyPath' => 'bool',
157
        'noPropertyPathMessage' => 'array',
158
        'skipOnEmpty' => 'bool',
159
        'skipOnError' => 'bool',
160
        'rules' => 'array',
161
    ])]
162
    public function getOptions(): array
163
    {
164
        return [
165
            'requirePropertyPath' => $this->getRequirePropertyPath(),
166
            'noPropertyPathMessage' => [
167
                'message' => $this->getNoPropertyPathMessage(),
168
            ],
169
            'skipOnEmpty' => $this->skipOnEmpty,
170
            'skipOnError' => $this->skipOnError,
171
            'rules' => (new RulesDumper())->asArray($this->rules),
172
        ];
173
    }
174
175
    public function getHandlerClassName(): string
176
    {
177
        return NestedHandler::class;
178
    }
179
}
180