Passed
Pull Request — master (#222)
by Rustam
02:28
created

NestedHandler::validate()   C

Complexity

Conditions 14
Paths 44

Size

Total Lines 60
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 14

Importance

Changes 0
Metric Value
eloc 35
dl 0
loc 60
ccs 35
cts 35
cp 1
rs 6.2666
c 0
b 0
f 0
cc 14
nc 44
nop 3
crap 14

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
use Yiisoft\Validator\Exception\UnexpectedRuleException;
9
use Yiisoft\Validator\Formatter;
10
use Yiisoft\Validator\FormatterInterface;
11
use Yiisoft\Validator\Result;
12
use Yiisoft\Validator\ValidationContext;
13
14
use function is_array;
15
use function is_object;
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 NestedHandler implements RuleHandlerInterface
43
{
44
    private FormatterInterface $formatter;
45
46 12
    public function __construct(?FormatterInterface $formatter = null)
47
    {
48 12
        $this->formatter = $formatter ?? new Formatter();
49
    }
50
51 12
    public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
52
    {
53 12
        if (!$rule instanceof Nested) {
54 1
            throw new UnexpectedRuleException(Nested::class, $rule);
55
        }
56
57 11
        $compoundResult = new Result();
58 11
        if (!is_object($value) && !is_array($value)) {
59 1
            $message = sprintf('Value should be an array or an object. %s given.', gettype($value));
60 1
            $formattedMessage = $this->formatter->format(
61
                $message,
62 1
                ['attribute' => $context?->getAttribute(), 'value' => $value]
63
            );
64 1
            $compoundResult->addError($formattedMessage);
65
66 1
            return $compoundResult;
67
        }
68
69 10
        $value = (array)$value;
70
71 10
        $results = [];
72 10
        foreach ($rule->getRules() as $valuePath => $rules) {
73 10
            $result = new Result();
74
75 10
            if ($rule->isErrorWhenPropertyPathIsNotFound() && !ArrayHelper::pathExists($value, $valuePath)) {
76 2
                $formattedMessage = $this->formatter->format(
77 2
                    $rule->getPropertyPathIsNotFoundMessage(),
78 2
                    ['path' => $valuePath, 'attribute' => $context?->getAttribute(), 'value' => $value]
79
                );
80 2
                $compoundResult->addError($formattedMessage, [$valuePath]);
81
82 2
                continue;
83
            }
84
85 8
            $rules = is_array($rules) ? $rules : [$rules];
86 8
            $validatedValue = ArrayHelper::getValueByPath($value, $valuePath);
87
88 8
            $itemResult = $context?->getValidator()->validate($validatedValue, $rules);
89
90 8
            if ($itemResult->isValid()) {
91 3
                continue;
92
            }
93
94 5
            foreach ($itemResult->getErrors() as $error) {
95 5
                $errorValuePath = is_int($valuePath) ? [$valuePath] : explode('.', $valuePath);
96 5
                if ($error->getValuePath()) {
97 2
                    $errorValuePath = array_merge($errorValuePath, $error->getValuePath());
98
                }
99 5
                $result->addError($error->getMessage(), $errorValuePath);
100
            }
101 5
            $results[] = $result;
102
        }
103
104 10
        foreach ($results as $result) {
105 5
            foreach ($result->getErrors() as $error) {
106 5
                $compoundResult->addError($error->getMessage(), $error->getValuePath());
107
            }
108
        }
109
110 10
        return $compoundResult;
111
    }
112
}
113