Passed
Pull Request — master (#279)
by Alexander
04:43 queued 02:12
created

Nested::normalizeRules()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 10.6588

Importance

Changes 0
Metric Value
eloc 18
c 0
b 0
f 0
dl 0
loc 31
ccs 11
cts 19
cp 0.5789
rs 8.8333
cc 7
nc 17
nop 0
crap 10.6588
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\Validator\BeforeValidationInterface;
13
use Yiisoft\Validator\Rule\Trait\BeforeValidationTrait;
14
use Yiisoft\Validator\Rule\Trait\RuleNameTrait;
15
use Yiisoft\Validator\RuleInterface;
16
use Yiisoft\Validator\RulesDumper;
17
use Yiisoft\Validator\SerializableRuleInterface;
18
use Yiisoft\Validator\ValidationContext;
19
20
use function array_pop;
21
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...
22
use function explode;
23
use function implode;
24
use function is_array;
25
use function sprintf;
26
27
/**
28
 * Can be used for validation of nested structures.
29
 */
30
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
31
final class Nested implements SerializableRuleInterface, BeforeValidationInterface
32
{
33
    use BeforeValidationTrait;
34
    use RuleNameTrait;
35
36 4
    public function __construct(
37
        /**
38
         * @var iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
39
         */
40
        private iterable $rules = [],
41
        private bool $requirePropertyPath = false,
42
        private string $noPropertyPathMessage = 'Property path "{path}" is not found.',
43
        private bool $skipOnEmpty = false,
44
        private bool $skipOnError = false,
45
        /**
46
         * @var Closure(mixed, ValidationContext):bool|null
47
         */
48
        private ?Closure $when = null,
49
    ) {
50 4
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
51 4
        if (empty($rules)) {
52 1
            throw new InvalidArgumentException('Rules must not be empty.');
53
        }
54
55 3
        if (self::checkRules($rules)) {
56 1
            $message = sprintf('Each rule should be an instance of %s.', RuleInterface::class);
57 1
            throw new InvalidArgumentException($message);
58
        }
59
60 2
        $this->rules = $rules;
61 2
        $this->normalizeRules();
62
    }
63
64
    /**
65
     * @return iterable<\Closure|\Closure[]|RuleInterface|RuleInterface[]>
66
     */
67 18
    public function getRules(): iterable
68
    {
69 18
        return $this->rules;
70
    }
71
72
    /**
73
     * @return bool
74
     */
75 22
    public function getRequirePropertyPath(): bool
76
    {
77 22
        return $this->requirePropertyPath;
78
    }
79
80
    /**
81
     * @return string
82
     */
83 7
    public function getNoPropertyPathMessage(): string
84
    {
85 7
        return $this->noPropertyPathMessage;
86
    }
87
88 3
    private static function checkRules($rules): bool
89
    {
90 3
        return array_reduce(
91
            $rules,
92 3
            function (bool $carry, $rule) {
93 3
                return $carry || (is_array($rule) ? self::checkRules($rule) : !$rule instanceof RuleInterface);
94
            },
95
            false
96
        );
97
    }
98
99 2
    private function normalizeRules(): void
100
    {
101 2
        while (true) {
102 2
            $breakWhile = true;
103 2
            $rulesMap = [];
104
105 2
            foreach ($this->rules as $valuePath => $rule) {
106 2
                $parts = explode('.*.', (string) $valuePath);
107 2
                if (count($parts) === 1) {
108 2
                    continue;
109
                }
110
111
                $breakWhile = false;
112
113
                $lastValuePath = array_pop($parts);
114
                $remainingValuePath = implode('.*.', $parts);
115
116
                if (!isset($rulesMap[$remainingValuePath])) {
117
                    $rulesMap[$remainingValuePath] = [];
118
                }
119
120
                $rulesMap[$remainingValuePath][$lastValuePath] = $rule;
121
                unset($this->rules[$valuePath]);
122
            }
123
124 2
            foreach ($rulesMap as $valuePath => $nestedRules) {
125
                $this->rules[$valuePath] = new Each([new self($nestedRules)]);
126
            }
127
128 2
            if ($breakWhile === true) {
129 2
                break;
130
            }
131
        }
132
    }
133
134 4
    #[ArrayShape([
135
        'requirePropertyPath' => 'bool',
136
        'noPropertyPathMessage' => 'array',
137
        'skipOnEmpty' => 'bool',
138
        'skipOnError' => 'bool',
139
        'rules' => 'array',
140
    ])]
141
    public function getOptions(): array
142
    {
143
        return [
144 4
            'requirePropertyPath' => $this->getRequirePropertyPath(),
145
            'noPropertyPathMessage' => [
146 4
                'message' => $this->getNoPropertyPathMessage(),
147
            ],
148 4
            'skipOnEmpty' => $this->skipOnEmpty,
149 4
            'skipOnError' => $this->skipOnError,
150 4
            'rules' => (new RulesDumper())->asArray($this->rules),
151
        ];
152
    }
153
154 8
    public function getHandlerClassName(): string
155
    {
156 8
        return NestedHandler::class;
157
    }
158
}
159