Passed
Pull Request — master (#279)
by Sergei
02:18
created

Nested::normalizeRules()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 49
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 12.3275

Importance

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