Passed
Pull Request — master (#175)
by Alexander
02:36
created

Validator::validate()   A

Complexity

Conditions 6
Paths 20

Size

Total Lines 30
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 6.0493

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 17
c 1
b 0
f 0
nc 20
nop 2
dl 0
loc 30
ccs 16
cts 18
cp 0.8889
crap 6.0493
rs 9.0777
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Validator\DataSet\ArrayDataSet;
8
use Yiisoft\Validator\DataSet\ScalarDataSet;
9
use function is_array;
10
use function is_object;
11
12
/**
13
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
14
 */
15
final class Validator implements ValidatorInterface
16
{
17
    private ?FormatterInterface $formatter;
18
19 12
    public function __construct(?FormatterInterface $formatter = null)
20
    {
21 12
        $this->formatter = $formatter;
22
    }
23
24
    /**
25
     * @param DataSetInterface|mixed|RulesProviderInterface $data
26
     * @param Rule[][] $rules
27
     * @psalm-param iterable<string, Rule[]> $rules
28
     */
29 12
    public function validate($data, iterable $rules = []): Result
30
    {
31 12
        $data = $this->normalizeDataSet($data);
32 12
        if ($data instanceof RulesProviderInterface) {
33 2
            $rules = $data->getRules();
34
        }
35
36 12
        $context = new ValidationContext($data);
37 12
        $result = new Result();
38
39 12
        foreach ($rules as $attribute => $attributeRules) {
40 12
            $ruleSet = new RuleSet($attributeRules);
41 12
            if ($this->formatter !== null) {
42
                $ruleSet = $ruleSet->withFormatter($this->formatter);
43
            }
44
45 12
            $tempResult = $ruleSet->validate(
46 12
                $data->getAttributeValue($attribute),
47 12
                $context->withAttribute($attribute)
48
            );
49 12
            foreach ($tempResult->getErrors() as $error) {
50 3
                $result->addError($error->getMessage(), [$attribute, ...$error->getValuePath()]);
51
            }
52
        }
53
54 12
        if ($data instanceof PostValidationHookInterface) {
55
            $data->processValidationResult($result);
56
        }
57
58 12
        return $result;
59
    }
60
61
    public function withFormatter(?FormatterInterface $formatter): self
62
    {
63
        $new = clone $this;
64
        $new->formatter = $formatter;
65
        return $new;
66
    }
67
68 12
    private function normalizeDataSet($data): DataSetInterface
69
    {
70 12
        if ($data instanceof DataSetInterface) {
71 5
            return $data;
72
        }
73
74 7
        if (is_object($data) || is_array($data)) {
75 1
            return new ArrayDataSet((array) $data);
76
        }
77
78 6
        return new ScalarDataSet($data);
79
    }
80
}
81