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

Validator::validate()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.0592

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 12
nop 2
dl 0
loc 22
ccs 13
cts 15
cp 0.8667
crap 5.0592
rs 9.4888
c 0
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 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