Passed
Pull Request — master (#102)
by Sergei
01:51
created

Validator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 72.21%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 38
ccs 13
cts 18
cp 0.7221
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 15 3
A withFormatter() 0 5 1
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
        $context = new ValidationContext($dataSet);
29 1
        $results = new ResultSet();
30 1
        foreach ($rules as $attribute => $attributeRules) {
31 1
            $aggregateRule = new Rules($attributeRules);
32 1
            if ($this->formatter !== null) {
33
                $aggregateRule = $aggregateRule->withFormatter($this->formatter);
34
            }
35 1
            $results->addResult(
36 1
                $attribute,
37 1
                $aggregateRule->validate($dataSet->getAttributeValue($attribute), $context)
38
            );
39
        }
40 1
        return $results;
41
    }
42
43
    public function withFormatter(?FormatterInterface $formatter): self
44
    {
45
        $new = clone $this;
46
        $new->formatter = $formatter;
47
        return $new;
48
    }
49
}
50