Passed
Pull Request — master (#97)
by Sergei
01:55
created

Validator::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
nc 3
nop 2
dl 0
loc 14
ccs 9
cts 10
cp 0.9
crap 3.009
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
/**
8
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
9
 */
10
final class Validator implements ValidatorInterface
11
{
12
    private ?FormatterInterface $formatter;
13
14 1
    public function __construct(?FormatterInterface $formatter = null)
15
    {
16 1
        $this->formatter = $formatter;
17 1
    }
18
19
    /**
20
     * @param DataSetInterface $dataSet
21
     * @param Rule[][] $rules
22
     * @psalm-param iterable<string, Rule[]> $rules
23
     *
24
     * @return ResultSet
25
     */
26 1
    public function validate(DataSetInterface $dataSet, iterable $rules): ResultSet
27
    {
28 1
        $results = new ResultSet();
29 1
        foreach ($rules as $attribute => $attributeRules) {
30 1
            $aggregateRule = new Rules($attributeRules);
31 1
            if ($this->formatter !== null) {
32
                $aggregateRule = $aggregateRule->withFormatter($this->formatter);
33
            }
34 1
            $results->addResult(
35 1
                $attribute,
36 1
                $aggregateRule->validate($dataSet->getAttributeValue($attribute), $dataSet)
37
            );
38
        }
39 1
        return $results;
40
    }
41
42
    public function withFormatter(?FormatterInterface $formatter): self
43
    {
44
        $new = clone $this;
45
        $new->formatter = $formatter;
46
        return $new;
47
    }
48
}
49