Passed
Push — master ( cd2db1...fdabae )
by Alexander
02:29
created

Nested::getRequirePropertyPath()   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 Traversable;
12
use Yiisoft\Strings\StringHelper;
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
#[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 6
    public function __construct(
42
        /**
43
         * @var iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
44
         */
45
        private iterable $rules = [],
46
        private bool $requirePropertyPath = false,
47
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
48
        private bool $normalizeRules = true,
49
        private bool $skipOnEmpty = false,
50
        /**
51
         * @var callable
52
         */
53
        private $skipOnEmptyCallback = null,
54
        private bool $skipOnError = false,
55
        /**
56
         * @var Closure(mixed, ValidationContext):bool|null
57
         */
58
        private ?Closure $when = null,
59
    ) {
60 6
        $this->initSkipOnEmptyProperties($skipOnEmpty, $skipOnEmptyCallback);
61
62 6
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
63 6
        if (empty($rules)) {
64 1
            throw new InvalidArgumentException('Rules must not be empty.');
65
        }
66
67 5
        if (self::checkRules($rules)) {
68 1
            $message = sprintf('Each rule should be an instance of %s.', RuleInterface::class);
69 1
            throw new InvalidArgumentException($message);
70
        }
71
72 4
        $this->rules = $rules;
73
74 4
        if ($this->normalizeRules === true) {
75 4
            $this->normalizeRules();
76
        }
77
    }
78
79
    /**
80
     * @return iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
81
     */
82 27
    public function getRules(): iterable
83
    {
84 27
        return $this->rules;
85
    }
86
87
    /**
88
     * @return bool
89
     */
90 27
    public function getRequirePropertyPath(): bool
91
    {
92 27
        return $this->requirePropertyPath;
93
    }
94
95
    /**
96
     * @return string
97
     */
98 7
    public function getNoPropertyPathMessage(): string
99
    {
100 7
        return $this->noPropertyPathMessage;
101
    }
102
103 5
    private static function checkRules($rules): bool
104
    {
105 5
        return array_reduce(
106
            $rules,
107 5
            function (bool $carry, $rule) {
108 5
                return $carry || (is_array($rule) ? self::checkRules($rule) : !$rule instanceof RuleInterface);
109
            },
110
            false
111
        );
112
    }
113
114 4
    private function normalizeRules(): void
115
    {
116
        /** @var iterable $rules */
117 4
        $rules = $this->getRules();
118 4
        while (true) {
119 4
            $breakWhile = true;
120 4
            $rulesMap = [];
121
122 4
            foreach ($rules as $valuePath => $rule) {
123 4
                if ($valuePath === self::EACH_SHORTCUT) {
124 1
                    throw new InvalidArgumentException('Bare shortcut is prohibited. Use "Each" rule instead.');
125
                }
126
127 3
                $parts = StringHelper::parsePath(
128 3
                    (string) $valuePath,
129
                    delimiter: self::EACH_SHORTCUT,
130
                    preserveDelimiterEscaping: true
131
                );
132 3
                if (count($parts) === 1) {
133 3
                    continue;
134
                }
135
136
                $breakWhile = false;
137
138
                $lastValuePath = array_pop($parts);
139
                $lastValuePath = ltrim($lastValuePath, '.');
140
                $lastValuePath = str_replace('\\' . self::EACH_SHORTCUT, self::EACH_SHORTCUT, $lastValuePath);
141
142
                $remainingValuePath = implode(self::EACH_SHORTCUT, $parts);
143
                $remainingValuePath = rtrim($remainingValuePath, self::SEPARATOR);
144
145
                if (!isset($rulesMap[$remainingValuePath])) {
146
                    $rulesMap[$remainingValuePath] = [];
147
                }
148
149
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
150
                unset($rules[$valuePath]);
151
            }
152
153 3
            foreach ($rulesMap as $valuePath => $nestedRules) {
154
                $rules[$valuePath] = new Each([new self($nestedRules, normalizeRules: false)]);
155
            }
156
157 3
            if ($breakWhile === true) {
158 3
                break;
159
            }
160
        }
161
162 3
        $this->rules = $rules;
163
    }
164
165 4
    #[ArrayShape([
166
        'requirePropertyPath' => 'bool',
167
        'noPropertyPathMessage' => 'array',
168
        'skipOnEmpty' => 'bool',
169
        'skipOnError' => 'bool',
170
        'rules' => 'array',
171
    ])]
172
    public function getOptions(): array
173
    {
174
        return [
175 4
            'requirePropertyPath' => $this->getRequirePropertyPath(),
176
            'noPropertyPathMessage' => [
177 4
                'message' => $this->getNoPropertyPathMessage(),
178
            ],
179 4
            'skipOnEmpty' => $this->skipOnEmpty,
180 4
            'skipOnError' => $this->skipOnError,
181 4
            'rules' => (new RulesDumper())->asArray($this->rules),
182
        ];
183
    }
184
185 11
    public function getHandlerClassName(): string
186
    {
187 11
        return NestedHandler::class;
188
    }
189
}
190