Passed
Pull Request — master (#222)
by Dmitriy
02:36
created

NestedValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 26
c 1
b 0
f 0
dl 0
loc 50
ccs 27
cts 27
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C validate() 0 48 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule\Nested;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule\AtLeast\AtLeast;
10
use Yiisoft\Validator\Rule\RuleValidatorInterface;
11
use Yiisoft\Validator\ValidationContext;
12
use Yiisoft\Validator\ValidatorInterface;
13
use function is_array;
14
use function is_object;
15
use Yiisoft\Validator\Exception\UnexpectedRuleException;
16
17
/**
18
 * 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 we can configure it like this:
32
 *
33
 * ```php
34
 * $rule = new Nested([
35
 *     'author' => new Nested([
36
 *         'name' => [new HasLength(min: 3)],
37
 *         'age' => [new Number(min: 18)],
38
 *     )];
39
 * ]);
40
 * ```
41
 */
42
final class NestedValidator implements RuleValidatorInterface
43
{
44 12
    public function validate(mixed $value, object $rule, ValidatorInterface $validator, ?ValidationContext $context = null): Result
45
    {
46 12
        if (!$rule instanceof Nested) {
47 1
            throw new UnexpectedRuleException(Nested::class, $rule);
48
        }
49
50 11
        $compoundResult = new Result();
51 11
        if (!is_object($value) && !is_array($value)) {
52 1
            $message = sprintf('Value should be an array or an object. %s given.', gettype($value));
53 1
            $compoundResult->addError($message);
54
55 1
            return $compoundResult;
56
        }
57
58 10
        $value = (array)$value;
59
60 10
        $results = [];
61 10
        foreach ($rule->rules as $valuePath => $rules) {
62 10
            $result = new Result((string)$valuePath);
63
64 10
            if ($rule->errorWhenPropertyPathIsNotFound && !ArrayHelper::pathExists($value, $valuePath)) {
65 2
                $compoundResult->addError($rule->propertyPathIsNotFoundMessage, ['path' => $valuePath], $valuePath);
66
67 2
                continue;
68
            }
69
70 8
            $rules = is_array($rules) ? $rules : [$rules];
71 8
            $validatedValue = ArrayHelper::getValueByPath($value, $valuePath);
72
73 8
            $itemResult = $validator->validate($validatedValue, $rules);
74
75 8
            if ($itemResult->isValid()) {
76 3
                continue;
77
            }
78
79 5
            foreach ($itemResult->getErrors() as $error) {
80 5
                $result->merge($error);
81
            }
82 5
            $results[] = $result;
83
        }
84
85 10
        foreach ($results as $result) {
86 5
            foreach ($result->getErrors() as $error) {
87 5
                $compoundResult->merge($error);
88
            }
89
        }
90
91 10
        return $compoundResult;
92
    }
93
}
94