Passed
Pull Request — master (#98)
by Alexander
02:00
created

Nested::propertyPathIsNotFoundMessage()   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
15
/**
16
 * Nested rule needed for validation nested structures.
17
 *
18
 * For example we have an inbound request with the following structure:
19
 * $request = [
20
 *     'author' => [
21
 *         'name' => 'Dmitry',
22
 *         'age' => 18,
23
 *     ],
24
 * ];
25
 *
26
 * So to make validation with Nested rule we can configure it like this:
27
 * $rule = new Nested([
28
 *     'author.age' => [
29
 *         (new Number())->min(20),
30
 *     ],
31
 *     'author.name' => [
32
 *         (new HasLength())->min(3),
33
 *     ],
34
 * ]);
35
 */
36
class Nested extends Rule
37
{
38
    /**
39
     * @var Rule[][]
40
     */
41
    private iterable $rules;
42
43
    private bool $errorWhenPropertyPathIsNotFound = false;
44
    private string $propertyPathIsNotFoundMessage = 'Property path "{path}" is not found.';
45
46 11
    public function __construct(iterable $rules)
47
    {
48 11
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
49 11
        if (empty($rules)) {
50 1
            throw new InvalidArgumentException('Rules should not be empty.');
51
        }
52 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

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