Passed
Push — master ( d3f54d...5f41a8 )
by Alexander
07:49
created

Validator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 72.72%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 45
ccs 16
cts 22
cp 0.7272
rs 10
c 0
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A withFormatter() 0 5 1
A validate() 0 22 5
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
        $resultSet = 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
            $resultSet->addResult(
40 4
                $attribute,
41 4
                $aggregateRule->validate($dataSet->getAttributeValue($attribute), $context->withAttribute($attribute))
42
            );
43
        }
44 4
        if ($dataSet instanceof PostValidationHookInterface) {
45
            $dataSet->processValidationResult($resultSet);
46
        }
47 4
        return $resultSet;
48
    }
49
50
    public function withFormatter(?FormatterInterface $formatter): self
51
    {
52
        $new = clone $this;
53
        $new->formatter = $formatter;
54
        return $new;
55
    }
56
}
57