Passed
Pull Request — master (#151)
by
unknown
02:41
created

Nested::calculateErrorKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 3
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
rs 10
c 1
b 0
f 0
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\Strings\NumericHelper;
11
use Yiisoft\Validator\ParametrizedRuleInterface;
12
use Yiisoft\Validator\Result;
13
use Yiisoft\Validator\Rule;
14
use Yiisoft\Validator\RuleInterface;
15
use Yiisoft\Validator\Rules;
16
use Yiisoft\Validator\ValidationContext;
17
use function is_array;
18
use function is_object;
19
20
/**
21
 * Nested rule can be used for validation of nested structures.
22
 *
23
 * For example we have an inbound request with the following structure:
24
 *
25
 * ```php
26
 * $request = [
27
 *     'author' => [
28
 *         'name' => 'Dmitry',
29
 *         'age' => 18,
30
 *     ],
31
 * ];
32
 * ```
33
 *
34
 * So to make validation with Nested rule we can configure it like this:
35
 *
36
 * ```php
37
 * $rule = Nested::rule([
38
 *     'author' => Nested::rule([
39
 *         'name' => [HasLength::rule()->min(3)],
40
 *         'age' => [Number::rule()->min(18)],
41
 *     )];
42
 * ]);
43
 * ```
44
 */
45
final class Nested extends Rule
46
{
47
    /**
48
     * @var Rule[][]
49
     */
50
    private iterable $rules;
51
52
    private bool $errorWhenPropertyPathIsNotFound = false;
53
    private string $propertyPathIsNotFoundMessage = 'Property path "{path}" is not found.';
54
55 14
    public static function rule(iterable $rules): self
56
    {
57 14
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
58 14
        if (empty($rules)) {
59 1
            throw new InvalidArgumentException('Rules should not be empty.');
60
        }
61
62 13
        $rule = new self();
63 13
        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

63
        if ($rule->checkRules(/** @scrutinizer ignore-type */ $rules)) {
Loading history...
64 1
            throw new InvalidArgumentException(sprintf(
65 1
                'Each rule should be an instance of %s.',
66 1
                RuleInterface::class
67
            ));
68
        }
69
70 12
        $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...
71
72 12
        return $rule;
73
    }
74
75 9
    protected function validateValue($value, ValidationContext $context = null): Result
76
    {
77 9
        $result = new Result();
78 9
        if (!is_object($value) && !is_array($value)) {
79 1
            $result->addError(sprintf(
80 1
                'Value should be an array or an object. %s given.',
81 1
                gettype($value)
82
            ));
83 1
            return $result;
84
        }
85 8
        $value = (array) $value;
86
87 8
        foreach ($this->rules as $valuePath => $rules) {
88 8
            $rulesSet = is_array($rules) ? $rules : [$rules];
89 8
            if ($this->errorWhenPropertyPathIsNotFound && !ArrayHelper::pathExists($value, $valuePath)) {
90 2
                $result->addError(
91 2
                    $this->formatMessage(
92 2
                        $this->propertyPathIsNotFoundMessage,
93
                        [
94 2
                            'path' => $valuePath,
95
                        ]
96
                    )
97
                );
98 2
                continue;
99
            }
100 6
            $validatedValue = ArrayHelper::getValueByPath($value, $valuePath);
101 6
            $aggregatedRule = new Rules($rulesSet);
102 6
            $itemResult = $aggregatedRule->validate($validatedValue);
103 6
            if ($itemResult->isValid()) {
104 3
                continue;
105
            }
106
107 4
            $concatenateErrorKey = !isset($itemResult->getErrors()[0]) || $aggregatedRule->isNestedEach();
108
109 4
            foreach ($itemResult->getErrors() as $key => $error) {
110 4
                $errorKey = $concatenateErrorKey ? "$valuePath.$key" : $valuePath;
111 4
                $result->addError($error, $errorKey);
112
            }
113
        }
114
115 8
        return $result;
116
    }
117
118
    /**
119
     * @param bool $value If absence of nested property should be considered an error. Default is `false`.
120
     *
121
     * @return self
122
     */
123 2
    public function errorWhenPropertyPathIsNotFound(bool $value): self
124
    {
125 2
        $new = clone $this;
126 2
        $new->errorWhenPropertyPathIsNotFound = $value;
127 2
        return $new;
128
    }
129
130
    /**
131
     * @param string $message A message to use when nested property is absent.
132
     *
133
     * @return $this
134
     */
135 1
    public function propertyPathIsNotFoundMessage(string $message): self
136
    {
137 1
        $new = clone $this;
138 1
        $new->propertyPathIsNotFoundMessage = $message;
139 1
        return $new;
140
    }
141
142 2
    public function getOptions(): array
143
    {
144 2
        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

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