Passed
Pull Request — master (#98)
by Alexander
03:47 queued 01:41
created

Nested::errorWhenPropertyPathIsNotFound()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
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\DataSetInterface;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\Rule;
13
use Yiisoft\Validator\Rules;
14
use function is_array;
15
use function is_object;
16
17
/**
18
 * Nested rule can be used for validation of nested structures.
19
 *
20
 * For example we have an inbound request with the following structure:
21
 *
22
 * ```php
23
 * $request = [
24
 *     'author' => [
25
 *         'name' => 'Dmitry',
26
 *         'age' => 18,
27
 *     ],
28
 * ];
29
 * ```
30
 *
31
 * So to make validation with Nested rule we can configure it like this:
32
 *
33
 * ```php
34
 * $rule = new Nested([
35
 *     'author.age' => [
36
 *         (new Number())->min(20),
37
 *     ],
38
 *     'author.name' => [
39
 *         (new HasLength())->min(3),
40
 *     ],
41
 * ]);
42
 * ```
43
 */
44
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 11
    public function __construct(iterable $rules)
55
    {
56 11
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
57 11
        if (empty($rules)) {
58 1
            throw new InvalidArgumentException('Rules should not be empty.');
59
        }
60 10
        if ($this->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

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