Passed
Pull Request — master (#116)
by Alexander
19:49 queued 06:25
created

Validator::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3.0052

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 2
dl 0
loc 16
ccs 11
cts 12
cp 0.9167
crap 3.0052
rs 9.9
c 0
b 0
f 0
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 8
    public function __construct(?FormatterInterface $formatter = null)
20
    {
21 8
        $this->formatter = $formatter;
22 8
    }
23
24
    /**
25
     * @param DataSetInterface|mixed $data
26
     * @param Rule[][] $rules
27
     * @psalm-param iterable<string, Rule[]> $rules
28
     *
29
     * @return ResultSet
30
     */
31 8
    public function validate($data, iterable $rules): ResultSet
32
    {
33 8
        $data = $this->normalizeDataSet($data);
34 8
        $context = new ValidationContext($data);
35 8
        $results = new ResultSet();
36 8
        foreach ($rules as $attribute => $attributeRules) {
37 8
            $aggregateRule = new Rules($attributeRules);
38 8
            if ($this->formatter !== null) {
39
                $aggregateRule = $aggregateRule->withFormatter($this->formatter);
40
            }
41 8
            $results->addResult(
42 8
                $attribute,
43 8
                $aggregateRule->validate($data->getAttributeValue($attribute), $context->withAttribute($attribute))
44
            );
45
        }
46 8
        return $results;
47
    }
48
49
    public function withFormatter(?FormatterInterface $formatter): self
50
    {
51
        $new = clone $this;
52
        $new->formatter = $formatter;
53
        return $new;
54
    }
55
56 8
    private function normalizeDataSet($data): DataSetInterface
57
    {
58 8
        if ($data instanceof DataSetInterface) {
59 1
            return $data;
60
        }
61
62 7
        if (is_object($data) || is_array($data)) {
63 1
            return new ArrayDataSet((array)$data);
64
        }
65
66 6
        return new ScalarDataSet($data);
67
    }
68
}
69