Passed
Pull Request — master (#175)
by Alexander
02:36
created

Nested   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 130
Duplicated Lines 0 %

Test Coverage

Coverage 94.92%

Importance

Changes 9
Bugs 2 Features 0
Metric Value
eloc 60
dl 0
loc 130
ccs 56
cts 59
cp 0.9492
rs 10
c 9
b 2
f 0
wmc 26

7 Methods

Rating   Name   Duplication   Size   Complexity  
A rule() 0 18 4
A getOptions() 0 3 1
A errorWhenPropertyPathIsNotFound() 0 5 1
A propertyPathIsNotFoundMessage() 0 5 1
A checkRules() 0 6 3
B validateValue() 0 41 11
A fetchOptions() 0 19 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use InvalidArgumentException;
8
use Traversable;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Validator\ParametrizedRuleInterface;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
use Yiisoft\Validator\RuleInterface;
14
use Yiisoft\Validator\RuleSet;
15
use Yiisoft\Validator\ValidationContext;
16
use function is_array;
17
use function is_object;
18
19
/**
20
 * Nested rule can be used for validation of nested structures.
21
 *
22
 * For example we have an inbound request with the following structure:
23
 *
24
 * ```php
25
 * $request = [
26
 *     'author' => [
27
 *         'name' => 'Dmitry',
28
 *         'age' => 18,
29
 *     ],
30
 * ];
31
 * ```
32
 *
33
 * So to make validation with Nested rule we can configure it like this:
34
 *
35
 * ```php
36
 * $rule = Nested::rule([
37
 *     'author' => Nested::rule([
38
 *         'name' => [HasLength::rule()->min(3)],
39
 *         'age' => [new Number(min: 18)],
40
 *     )];
41
 * ]);
42
 * ```
43
 */
44
final class Nested extends Rule
45
{
46
    /**
47
     * @var Rule[][]
48
     */
49
    private iterable $rules;
50
51
    private bool $errorWhenPropertyPathIsNotFound = false;
52
    private string $propertyPathIsNotFoundMessage = 'Property path "{path}" is not found.';
53
54 17
    public static function rule(iterable $rules): self
55
    {
56 17
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
57 17
        if (empty($rules)) {
58 1
            throw new InvalidArgumentException('Rules should not be empty.');
59
        }
60
61 16
        $rule = new self();
62 16
        if ($rule->checkRules($rules)) {
0 ignored issues
show
Bug introduced by
It seems like $rules can also be of type iterable; however, parameter $rules of Yiisoft\Validator\Rule\Nested::checkRules() does only seem to accept array, 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

62
        if ($rule->checkRules(/** @scrutinizer ignore-type */ $rules)) {
Loading history...
63 1
            throw new InvalidArgumentException(sprintf(
64 1
                'Each rule should be an instance of %s.',
65
                RuleInterface::class
66
            ));
67
        }
68
69 15
        $rule->rules = $rules;
0 ignored issues
show
Documentation Bug introduced by
It seems like $rules can also be of type iterable. However, the property $rules is declared as type array<mixed,Yiisoft\Validator\Rule[]>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
70
71 15
        return $rule;
72
    }
73
74 11
    protected function validateValue($value, ?ValidationContext $context = null): Result
75
    {
76 11
        $result = new Result();
77 11
        if (!is_object($value) && !is_array($value)) {
78 1
            $result->addError(sprintf(
79 1
                'Value should be an array or an object. %s given.',
80 1
                gettype($value)
81
            ));
82
83 1
            return $result;
84
        }
85
86 10
        $value = (array) $value;
87
88 10
        foreach ($this->rules as $valuePath => $rules) {
89 10
            if ($this->errorWhenPropertyPathIsNotFound && !ArrayHelper::pathExists($value, $valuePath)) {
90 2
                $message = $this->formatMessage($this->propertyPathIsNotFoundMessage, ['path' => $valuePath]);
91 2
                $result->addError($message);
92
93 2
                continue;
94
            }
95
96 8
            $rules = is_array($rules) ? $rules : [$rules];
97 8
            $ruleSet = new RuleSet($rules);
98 8
            $validatedValue = ArrayHelper::getValueByPath($value, $valuePath);
99 8
            $itemResult = $ruleSet->validate($validatedValue);
100 8
            if ($itemResult->isValid()) {
101 3
                continue;
102
            }
103
104 6
            foreach ($itemResult->getErrors() as $error) {
105 6
                $errorValuePath = is_int($valuePath) ? [$valuePath] : explode('.', $valuePath);
106 6
                if ($error->getValuePath()) {
107 3
                    $errorValuePath = array_merge($errorValuePath, $error->getValuePath());
108
                }
109
110 6
                $result->addError($error->getMessage(), $errorValuePath);
111
            }
112
        }
113
114 10
        return $result;
115
    }
116
117
    /**
118
     * @param bool $value If absence of nested property should be considered an error. Default is `false`.
119
     *
120
     * @return self
121
     */
122 2
    public function errorWhenPropertyPathIsNotFound(bool $value): self
123
    {
124 2
        $new = clone $this;
125 2
        $new->errorWhenPropertyPathIsNotFound = $value;
126 2
        return $new;
127
    }
128
129
    /**
130
     * @param string $message A message to use when nested property is absent.
131
     *
132
     * @return $this
133
     */
134 1
    public function propertyPathIsNotFoundMessage(string $message): self
135
    {
136 1
        $new = clone $this;
137 1
        $new->propertyPathIsNotFoundMessage = $message;
138 1
        return $new;
139
    }
140
141 3
    public function getOptions(): array
142
    {
143 3
        return $this->fetchOptions($this->rules);
0 ignored issues
show
Bug introduced by
$this->rules of type iterable is incompatible with the type array expected by parameter $rules of Yiisoft\Validator\Rule\Nested::fetchOptions(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

143
        return $this->fetchOptions(/** @scrutinizer ignore-type */ $this->rules);
Loading history...
144
    }
145
146 16
    private function checkRules(array $rules): bool
147
    {
148 16
        return array_reduce(
149
            $rules,
150 16
            fn (bool $carry, $rule) => $carry || (is_array($rule) ? $this->checkRules($rule) : !$rule instanceof RuleInterface),
151
            false
152
        );
153
    }
154
155 3
    private function fetchOptions(array $rules): array
156
    {
157 3
        $result = [];
158 3
        foreach ($rules as $attribute => $rule) {
159 3
            if (is_array($rule)) {
160 2
                $result[$attribute] = $this->fetchOptions($rule);
161 3
            } elseif ($rule instanceof ParametrizedRuleInterface) {
162 3
                $result[$attribute] = $rule->getOptions();
163
            } elseif ($rule instanceof RuleInterface) {
164
                // Just skip the rule that doesn't support parametrizing
165
            } else {
166
                throw new \InvalidArgumentException(sprintf(
167
                    'Rules should be an array of rules that implements %s.',
168
                    ParametrizedRuleInterface::class,
169
                ));
170
            }
171
        }
172
173 3
        return $result;
174
    }
175
}
176