Passed
Pull Request — master (#317)
by Alexander
27:14 queued 24:41
created

Nested::propagateOptions()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

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

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