Test Failed
Pull Request — master (#98)
by Dmitriy
02:36
created

Nested::errorWhenPropertyPathIsNotFound()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
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
 * Each validator validates an array by checking each of its elements against a set of rules
17
 */
18
class Nested extends Rule
19
{
20
    /**
21
     * @var Rule[][]
22
     */
23
    private iterable $rules;
24
25
    private bool $errorWhenPropertyPathIsNotFound = false;
26
    private string $propertyPathIsNotFoundMessage = 'Property path "{path}" is not found.';
27
28
    public function __construct(iterable $rules)
29
    {
30
        $rules = $rules instanceof Traversable ? iterator_to_array($rules) : $rules;
31
        if (empty($rules)) {
32
            throw new InvalidArgumentException('Rules should not be empty.');
33
        }
34
        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

34
        if ($this->checkRules(/** @scrutinizer ignore-type */ $rules)) {
Loading history...
35
            throw new InvalidArgumentException(sprintf(
36
                'Each rule should be instance of %s.',
37
                Rule::class
38
            ));
39
        }
40
        $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...
41
    }
42
43
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
44
    {
45
        $result = new Result();
46
        if (!is_object($value) && !is_array($value)) {
47
            $result->addError(sprintf(
48
                'Value should be an array or an object. %s given',
49
                gettype($value)
50
            ));
51
            return $result;
52
        }
53
        $value = (array) $value;
54
55
        foreach ($this->rules as $valuePath => $rules) {
56
            $rulesSet = is_array($rules) ? $rules : [$rules];
57
            if ($this->errorWhenPropertyPathIsNotFound && !ArrayHelper::pathExists($value, $valuePath)) {
58
                $result->addError(
59
                    $this->translateMessage(
0 ignored issues
show
Bug introduced by
The method translateMessage() does not exist on Yiisoft\Validator\Rule\Nested. ( Ignorable by Annotation )

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

59
                    $this->/** @scrutinizer ignore-call */ 
60
                           translateMessage(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
60
                        $this->propertyPathIsNotFoundMessage,
61
                        [
62
                            'path' => $valuePath,
63
                        ]
64
                    )
65
                );
66
                continue;
67
            }
68
            $validatedValue = ArrayHelper::getValueByPath($value, $valuePath);
69
            $aggregateRule = new Rules($rulesSet);
70
            $itemResult = $aggregateRule->validate($validatedValue);
71
            if ($itemResult->isValid() === false) {
72
                foreach ($itemResult->getErrors() as $error) {
73
                    $result->addError($error);
74
                }
75
            }
76
        }
77
78
        return $result;
79
    }
80
81
    public function errorWhenPropertyPathIsNotFound(bool $value): self
82
    {
83
        $new = clone $this;
84
        $new->errorWhenPropertyPathIsNotFound = $value;
85
        return $new;
86
    }
87
88
    public function propertyPathIsNotFoundMessage(string $message): self
89
    {
90
        $new = clone $this;
91
        $new->propertyPathIsNotFoundMessage = $message;
92
        return $new;
93
    }
94
95
    public function getOptions(): array
96
    {
97
        return $this->rules->asArray();
98
    }
99
100
    private function checkRules(array $rules): bool
101
    {
102
        return array_reduce(
103
            $rules,
104
            fn (bool $carry, $rule) => $carry || is_array($rule) ? $this->checkRules($rule) : !$rule instanceof Rule,
105
            false
106
        );
107
    }
108
}
109