Passed
Pull Request — master (#317)
by
unknown
02:22
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 SerializableRuleInterface, BeforeValidationInterface, SkipOnEmptyInterface,
40
    PropagateOptionsInterface
41
{
42
    use BeforeValidationTrait;
43
    use RuleNameTrait;
44
    use SkipOnEmptyTrait;
45
46
    private const SEPARATOR = '.';
47
    private const EACH_SHORTCUT = '*';
48
49
    /**
50
     * @var iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
51
     */
52
    private ?iterable $rules;
53
54 23
    public function __construct(
55
        /**
56
         * Rules for validate value that can be described by:
57
         * - object that implement {@see RulesProviderInterface};
58
         * - name of class from whose attributes their will be derived;
59
         * - array or object implementing the `Traversable` interface that contain {@see RuleInterface} implementations
60
         *   or closures.
61
         *
62
         * `$rules` can be null if validatable value is object. In this case rules will be derived from object via
63
         * `getRules()` method if object implement {@see RulesProviderInterface} or from attributes otherwise.
64
         *
65
         * @var class-string|iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|RulesProviderInterface|null
66
         */
67
        iterable|object|string|null $rules = null,
68
69
        /**
70
         * @var int What visibility levels to use when reading data and rules from validated object.
71
         */
72
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE
73
        | ReflectionProperty::IS_PROTECTED
74
        | ReflectionProperty::IS_PUBLIC,
75
        /**
76
         * @var int What visibility levels to use when reading rules from the class specified in {@see $rules}
77
         * attribute.
78
         */
79
        private int $rulesPropertyVisibility = ReflectionProperty::IS_PRIVATE
80
        | ReflectionProperty::IS_PROTECTED
81
        | ReflectionProperty::IS_PUBLIC,
82
        private bool $requirePropertyPath = false,
83
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
84
        private bool $normalizeRules = true,
85
        private bool $propagateOptions = false,
86
87
        /**
88
         * @var bool|callable|null
89
         */
90
        private $skipOnEmpty = null,
91
        private bool $skipOnError = false,
92
93
        /**
94
         * @var Closure(mixed, ValidationContext):bool|null
95
         */
96
        private ?Closure $when = null,
97
    ) {
98 23
        $this->prepareRules($rules);
99
    }
100
101
    /**
102
     * @return iterable<Closure|Closure[]|RuleInterface|RuleInterface[]>|null
103
     */
104 39
    public function getRules(): ?iterable
105
    {
106 39
        return $this->rules;
107
    }
108
109 8
    public function getPropertyVisibility(): int
110
    {
111 8
        return $this->propertyVisibility;
112
    }
113
114
    /**
115
     * @return bool
116
     */
117 33
    public function getRequirePropertyPath(): bool
118
    {
119 33
        return $this->requirePropertyPath;
120
    }
121
122
    /**
123
     * @return string
124
     */
125 9
    public function getNoPropertyPathMessage(): string
126
    {
127 9
        return $this->noPropertyPathMessage;
128
    }
129
130
    /**
131
     * @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...
132
     */
133 23
    private function prepareRules(iterable|object|string|null $source): void
134
    {
135 23
        if ($source === null) {
136 14
            $this->rules = null;
137
138 14
            return;
139
        }
140
141 9
        if ($source instanceof RulesProviderInterface) {
142 1
            $rules = $source->getRules();
143 8
        } elseif (!$source instanceof Traversable && !is_array($source)) {
144 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

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