Passed
Pull Request — master (#72)
by Wilmer
11:03
created

Validator::addRules()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 5
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Validator\Rule\Callback;
8
use Yiisoft\I18n\TranslatorInterface;
9
10
/**
11
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
12
 */
13
class Validator implements ValidatorInterface
14
{
15
    private ?TranslatorInterface $translator;
16
    private ?string $translationDomain;
17
    private ?string $translationLocale;
18
19
    /**
20
     * @var Rules[]
21
     */
22
    private array $attributeRules = [];
23
24 2
    public function __construct(
25
        TranslatorInterface $translator = null,
26
        string $translationDomain = null,
27
        string $translationLocale = null
28
    ) {
29
        $this->translator = $translator;
30 2
        $this->translationDomain = $translationDomain;
31 2
        $this->translationLocale = $translationLocale;
32 2
    }
33
34 2
    public function validate(DataSetInterface $dataSet): ResultSet
35 1
    {
36 1
        $results = new ResultSet();
37 1
        foreach ($this->attributeRules as $attribute => $rules) {
38
            $results->addResult(
39 1
                $attribute,
40
                $rules->validate($dataSet->getAttributeValue($attribute), $dataSet)
41
            );
42
        }
43
        return $results;
44 2
    }
45
46 2
    public function addRule(string $attribute, Rule $rule): void
47 2
    {
48 2
        if (!isset($this->attributeRules[$attribute])) {
49 2
            $this->attributeRules[$attribute] = new Rules(
50 2
                [],
51
                $this->translator,
52
                $this->translationDomain,
53 2
                $this->translationLocale
54
            );
55
        }
56 2
57
        $this->attributeRules[$attribute]->add($rule);
58 2
    }
59 2
60 2
    public function addRules(iterable $rules = []): void
61 2
    {
62 2
        foreach ($rules as $attribute => $ruleSets) {
63 2
            foreach ($ruleSets as $rule) {
64
                if (is_callable($rule)) {
65
                    $rule = new Callback($rule);
66
                }
67 2
                $this->addRule($attribute, $rule);
68
            }
69
        }
70
    }
71
}
72