Passed
Pull Request — master (#115)
by Dmitriy
02:02
created

Validator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 75%

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 42
ccs 15
cts 20
cp 0.75
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validate() 0 19 4
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 4
    public function __construct(?FormatterInterface $formatter = null)
15
    {
16 4
        $this->formatter = $formatter;
17 4
    }
18
19
    /**
20
     * @param DataSetInterface|RulesProviderInterface $dataSet
21
     * @param Rule[][] $rules
22
     * @psalm-param iterable<string, Rule[]> $rules
23
     *
24
     * @return ResultSet
25
     */
26 4
    public function validate(DataSetInterface $dataSet, iterable $rules = []): ResultSet
27
    {
28 4
        if ($dataSet instanceof RulesProviderInterface) {
29
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
30 2
            $rules = $dataSet->getRules();
31
        }
32 4
        $context = new ValidationContext($dataSet);
33 4
        $results = new ResultSet();
34 4
        foreach ($rules as $attribute => $attributeRules) {
35 4
            $aggregateRule = new Rules($attributeRules);
36 4
            if ($this->formatter !== null) {
37
                $aggregateRule = $aggregateRule->withFormatter($this->formatter);
38
            }
39 4
            $results->addResult(
40 4
                $attribute,
41 4
                $aggregateRule->validate($dataSet->getAttributeValue($attribute), $context->withAttribute($attribute))
42
            );
43
        }
44 4
        return $results;
45
    }
46
47
    public function withFormatter(?FormatterInterface $formatter): self
48
    {
49
        $new = clone $this;
50
        $new->formatter = $formatter;
51
        return $new;
52
    }
53
}
54