Passed
Pull Request — master (#142)
by Wilmer
02:07
created

Validator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
36 2
            $rules = $data->getRules();
37
        }
38
39 12
        $context = new ValidationContext($data);
40 12
        $results = new ResultSet();
41
42 12
        foreach ($rules as $attribute => $attributeRules) {
43 12
            $aggregateRule = new Rules($attributeRules);
44 12
            if ($this->formatter !== null) {
45
                $aggregateRule = $aggregateRule->withFormatter($this->formatter);
46
            }
47 12
            $results->addResult(
48 12
                $attribute,
49 12
                $aggregateRule->validate(
50 12
                    $data->getRawAttributeValue($attribute) ?? '',
51 12
                    $context->withAttribute($attribute),
52
                )
53
            );
54
        }
55 12
        if ($data instanceof PostValidationHookInterface) {
56
            $data->processValidationResult($results);
57
        }
58 12
        return $results;
59
    }
60
61
    public function withFormatter(?FormatterInterface $formatter): self
62
    {
63
        $new = clone $this;
64
        $new->formatter = $formatter;
65
        return $new;
66
    }
67
68 12
    private function normalizeDataSet($data): DataSetInterface
69
    {
70 12
        if ($data instanceof DataSetInterface) {
71 5
            return $data;
72
        }
73
74 7
        if (is_object($data) || is_array($data)) {
75 1
            return new ArrayDataSet((array)$data);
76
        }
77
78 6
        return new ScalarDataSet($data);
79
    }
80
}
81