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

Nested::validateValue()   B

Complexity

Conditions 9
Paths 10

Size

Total Lines 37
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 23
nc 10
nop 2
dl 0
loc 37
ccs 24
cts 24
cp 1
crap 9
rs 8.0555
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\Validator\ParametrizedRuleInterface;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
use Yiisoft\Validator\RuleInterface;
14
use Yiisoft\Validator\Rules;
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' => [Number::rule()->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 14
    public static function rule(iterable $rules): self
55
    {
56 14
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
57 14
        if (empty($rules)) {
58 1
            throw new InvalidArgumentException('Rules should not be empty.');
59
        }
60
61 13
        $rule = new self();
62 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

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

139
        return $this->fetchOptions(/** @scrutinizer ignore-type */ $this->rules);
Loading history...
140
    }
141
142 13
    private function checkRules(array $rules): bool
143
    {
144 13
        return array_reduce(
145 13
            $rules,
146 13
            fn (bool $carry, $rule) => $carry || (is_array($rule) ? $this->checkRules($rule) : !$rule instanceof RuleInterface),
147 13
            false
148
        );
149
    }
150
151 2
    private function fetchOptions(array $rules): array
152
    {
153 2
        $result = [];
154 2
        foreach ($rules as $attribute => $rule) {
155 2
            if (is_array($rule)) {
156 1
                $result[$attribute] = $this->fetchOptions($rule);
157 2
            } elseif ($rule instanceof ParametrizedRuleInterface) {
158 2
                $result[$attribute] = $rule->getOptions();
159
            } elseif ($rule instanceof RuleInterface) {
160
                // Just skip the rule that doesn't support parametrizing
161
            } else {
162
                throw new \InvalidArgumentException(sprintf(
163
                    'Rules should be an array of rules that implements %s.',
164
                    ParametrizedRuleInterface::class,
165
                ));
166
            }
167
        }
168
169 2
        return $result;
170
    }
171
172 4
    private static function calculateErrorKey(Rules $aggregatedRule, string $valuePath, string $key): string
173
    {
174 4
        if (!self::canConcatenateErrorKey($aggregatedRule, $key)) {
175 4
            return $valuePath;
176
        }
177
178 1
        return "$valuePath.$key";
179
    }
180
181 4
    private static function canConcatenateErrorKey(Rules $aggregatedRule, string $key): bool
182
    {
183 4
        if (!self::isPositiveInteger($key)) {
184 1
            return true;
185
        }
186
187 4
        $aggregatedRuleArray = $aggregatedRule->asArray();
188 4
        if (ArrayHelper::getValue($aggregatedRuleArray, [0, 0]) !== 'each') {
189 4
            return false;
190
        }
191
192 1
        return !(ArrayHelper::getValue($aggregatedRuleArray, [0, 1, 0]) === 'nested');
193
    }
194
195 4
    private static function isPositiveInteger(string $str): bool
196
    {
197 4
        if (!preg_match('/^\d$/', $str)) {
198 1
            return false;
199
        }
200
201 4
        return filter_var($str, FILTER_VALIDATE_INT, ['options' => ['min_range' => 0]]) !== false;
202
    }
203
}
204