Passed
Push — master ( 1ce067...27c9ca )
by Alexander
02:32
created

Validator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 95%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 45
ccs 19
cts 20
cp 0.95
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 24 5
A normalizeDataSet() 0 12 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use JetBrains\PhpStorm\Pure;
8
use Yiisoft\Validator\DataSet\ArrayDataSet;
9
use Yiisoft\Validator\DataSet\ScalarDataSet;
10
use function is_array;
11
use function is_object;
12
13
/**
14
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
15
 */
16
final class Validator implements ValidatorInterface
17
{
18
    /**
19
     * @param DataSetInterface|mixed|RulesProviderInterface $data
20
     * @param Rule[][] $rules
21
     * @psalm-param iterable<string, Rule[]> $rules
22
     */
23 12
    public function validate($data, iterable $rules = []): Result
24
    {
25 12
        $data = $this->normalizeDataSet($data);
26 12
        if ($data instanceof RulesProviderInterface) {
27 2
            $rules = $data->getRules();
28
        }
29
30 12
        $context = new ValidationContext($data);
31 12
        $result = new Result();
32
33 12
        foreach ($rules as $attribute => $attributeRules) {
34 12
            $ruleSet = new RuleSet($attributeRules);
35 12
            $tempResult = $ruleSet->validate($data->getAttributeValue($attribute), $context->withAttribute($attribute));
36
37 12
            foreach ($tempResult->getErrors() as $error) {
38 3
                $result->addError($error->getMessage(), [$attribute, ...$error->getValuePath()]);
39
            }
40
        }
41
42 12
        if ($data instanceof PostValidationHookInterface) {
43
            $data->processValidationResult($result);
44
        }
45
46 12
        return $result;
47
    }
48
49 12
    #[Pure]
50
    private function normalizeDataSet($data): DataSetInterface
51
    {
52 12
        if ($data instanceof DataSetInterface) {
53 5
            return $data;
54
        }
55
56 7
        if (is_object($data) || is_array($data)) {
57 1
            return new ArrayDataSet((array) $data);
58
        }
59
60 6
        return new ScalarDataSet($data);
61
    }
62
}
63