Passed
Pull Request — master (#152)
by
unknown
02:06
created

Validator::withFormatter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Validator\DataSet\ArrayDataSet;
8
use Yiisoft\Validator\DataSet\ScalarDataSet;
9
use function is_array;
10
use function is_object;
11
12
/**
13
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
14
 */
15
final class Validator implements ValidatorInterface
16
{
17
    private ?FormatterInterface $formatter;
18
19 12
    public function __construct(?FormatterInterface $formatter = null)
20
    {
21 12
        $this->formatter = $formatter;
22 12
    }
23
24
    /**
25
     * @param DataSetInterface|mixed|RulesProviderInterface $data
26
     * @param Rule[][] $rules
27
     * @psalm-param iterable<string, Rule[]> $rules
28
     *
29
     * @return ResultSet
30
     */
31 12
    public function validate($data, iterable $rules = []): ResultSet
32
    {
33 12
        $data = $this->normalizeDataSet($data);
34 12
        if ($data instanceof RulesProviderInterface) {
35 2
            $rules = $data->getRules();
36
        }
37
38 12
        $context = new ValidationContext($data);
39 12
        $resultSet = new ResultSet();
40
41 12
        foreach ($rules as $attribute => $attributeRules) {
42 12
            $aggregatedRule = new Rules($attributeRules);
43 12
            if ($this->formatter !== null) {
44
                $aggregatedRule = $aggregatedRule->withFormatter($this->formatter);
45
            }
46
47 12
            $resultSet->addResult(
48 12
                $attribute,
49 12
                $aggregatedRule->validate($data->getAttributeValue($attribute), $context->withAttribute($attribute))
50
            );
51
        }
52
53 12
        if ($data instanceof PostValidationHookInterface) {
54
            $data->processValidationResult($resultSet);
55
        }
56
57 12
        return $resultSet;
58
    }
59
60
    public function withFormatter(?FormatterInterface $formatter): self
61
    {
62
        $new = clone $this;
63
        $new->formatter = $formatter;
64
        return $new;
65
    }
66
67 12
    private function normalizeDataSet($data): DataSetInterface
68
    {
69 12
        if ($data instanceof DataSetInterface) {
70 5
            return $data;
71
        }
72
73 7
        if (is_object($data) || is_array($data)) {
74 1
            return new ArrayDataSet((array) $data);
75
        }
76
77 6
        return new ScalarDataSet($data);
78
    }
79
}
80