Passed
Pull Request — master (#300)
by Alexander
06:13 queued 03:06
created

Nested::getHandlerClassName()   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
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
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\BeforeValidationInterface;
15
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait;
16
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
17
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
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\ValidationContext;
25
26
use function array_pop;
27
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...
28
use function implode;
29
use function is_array;
30
use function ltrim;
31
use function rtrim;
32
use function sprintf;
33
34
/**
35
 * Can be used for validation of nested structures.
36
 */
37
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
38
final class Nested implements SerializableRuleInterface, BeforeValidationInterface, SkipOnEmptyInterface
39
{
40
    use BeforeValidationTrait;
41
    use RuleNameTrait;
42
    use SkipOnEmptyTrait;
43
44
    private const SEPARATOR = '.';
45
    private const EACH_SHORTCUT = '*';
46
47
    /**
48
     * @var iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
49
     */
50
    private ?iterable $rules = null;
51
52 21
    public function __construct(
53
        /**
54
         * Rules for validate value that can be described by:
55
         * - object that implement {@see RulesProviderInterface};
56
         * - name of class from whose attributes their will be derived;
57
         * - array or object implementing the `Traversable` interface that contain {@see RuleInterface} implementations
58
         *   or closures.
59
         *
60
         * `$rules` can be null if validatable value is object. In this case rules will be derived from object via
61
         * `getRules()` method if object implement {@see RulesProviderInterface} or from attributes otherwise.
62
         *
63
         * @var class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null
64
         */
65
        iterable|object|string|null $rules = null,
66
67
        /**
68
         * @var int What visibility levels to use when reading data and rules from validatable object.
69
         */
70
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
71
72
        /**
73
         * @var int What visibility levels to use when reading rules from the class specified in {@see $rules}
74
         * attribute.
75
         */
76
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC,
77
        private bool $requirePropertyPath = false,
78
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
79
        private bool $normalizeRules = true,
80
81
        /**
82
         * @var bool|callable|null
83
         */
84
        private $skipOnEmpty = null,
85
        private bool $skipOnError = false,
86
87
        /**
88
         * @var Closure(mixed, ValidationContext):bool|null
89
         */
90
        private ?Closure $when = null,
91
    ) {
92 21
        $this->rules = $this->prepareRules($rules);
93
    }
94
95
    /**
96
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
97
     */
98 39
    public function getRules(): ?iterable
99
    {
100 39
        return $this->rules;
101
    }
102
103 8
    public function getPropertyVisibility(): int
104
    {
105 8
        return $this->propertyVisibility;
106
    }
107
108
    /**
109
     * @return bool
110
     */
111 32
    public function getRequirePropertyPath(): bool
112
    {
113 32
        return $this->requirePropertyPath;
114
    }
115
116
    /**
117
     * @return string
118
     */
119 8
    public function getNoPropertyPathMessage(): string
120
    {
121 8
        return $this->noPropertyPathMessage;
122
    }
123
124
    /**
125
     * @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...
126
     */
127 21
    private function prepareRules(iterable|object|string|null $source): ?iterable
128
    {
129 21
        if ($source === null) {
130 14
            return null;
131
        }
132
133 7
        if ($source instanceof RulesProviderInterface) {
134 1
            $rules = $source->getRules();
135 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...
136
        }
137
138 6
        $isTraversable = $source instanceof Traversable;
139
140 6
        if (!$isTraversable && !is_array($source)) {
141 3
            return (new AttributesRulesProvider($source, $this->rulesPropertyVisibility))->getRules();
0 ignored issues
show
Bug Best Practice introduced by
The expression return new Yiisoft\Valid...Visibility)->getRules() returns the type array which is incompatible with the type-hinted return iterable|null.
Loading history...
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

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

145
        $rules = $isTraversable ? iterator_to_array(/** @scrutinizer ignore-type */ $source) : $source;
Loading history...
146
147 3
        if (self::checkRules($rules)) {
148 1
            $message = sprintf('Each rule should be an instance of %s.', RuleInterface::class);
149 1
            throw new InvalidArgumentException($message);
150
        }
151
152 2
        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 Traversable|array which is incompatible with the type-hinted return iterable|null.
Loading history...
153
    }
154
155 3
    private static function checkRules($rules): bool
156
    {
157 3
        return array_reduce(
158
            $rules,
159 3
            function (bool $carry, $rule) {
160 2
                return $carry || (is_array($rule) ? self::checkRules($rule) : !$rule instanceof RuleInterface);
161
            },
162
            false
163
        );
164
    }
165
166 3
    private function normalizeRules(iterable $sourceRules): array
167
    {
168 3
        $rules = $sourceRules instanceof Traversable ? iterator_to_array($sourceRules) : $sourceRules;
169 3
        while (true) {
170 3
            $breakWhile = true;
171 3
            $rulesMap = [];
172
173 3
            foreach ($rules as $valuePath => $rule) {
174 2
                if ($valuePath === self::EACH_SHORTCUT) {
175 1
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
176
                }
177
178 1
                $parts = StringHelper::parsePath(
179 1
                    (string) $valuePath,
180
                    delimiter: self::EACH_SHORTCUT,
181
                    preserveDelimiterEscaping: true
182
                );
183 1
                if (count($parts) === 1) {
184 1
                    continue;
185
                }
186
187
                $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 2
            foreach ($rulesMap as $valuePath => $nestedRules) {
205
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
206
            }
207
208 2
            if ($breakWhile === true) {
209 2
                break;
210
            }
211
        }
212
213 2
        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 4
    #[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 4
            'requirePropertyPath' => $this->getRequirePropertyPath(),
227
            'noPropertyPathMessage' => [
228 4
                'message' => $this->getNoPropertyPathMessage(),
229
            ],
230 4
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
231 4
            'skipOnError' => $this->skipOnError,
232 4
            'rules' => $this->rules === null ? null : (new RulesDumper())->asArray($this->rules),
233
        ];
234
    }
235
236 24
    public function getHandlerClassName(): string
237
    {
238 24
        return NestedHandler::class;
239
    }
240
}
241