Passed
Pull Request — master (#41)
by Alexander
01:57 queued 36s
created

Validator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 40
ccs 0
cts 16
cp 0
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 4
A validate() 0 7 2
A addRule() 0 8 2
1
<?php
2
3
4
namespace Yiisoft\Validator;
5
6
use Yiisoft\Validator\Rule\Callback;
7
8
/**
9
 * Validator validates {@link DataSetInterface} against rules set for data set attributes.
10
 */
11
class Validator
12
{
13
    /**
14
     * @var Rules[]
15
     */
16
    private $attributeRules;
17
18
    /**
19
     * Validator constructor.
20
     * @param $rules
21
     */
22
    public function __construct(iterable $rules = [])
23
    {
24
        foreach ($rules as $attribute => $ruleSets) {
25
            foreach ($ruleSets as $rule) {
26
                if (is_callable($rule)) {
27
                    $rule = new Callback($rule);
28
                }
29
                $this->addRule($attribute, $rule);
30
            }
31
        }
32
    }
33
34
    public function validate(DataSetInterface $dataSet): ResultSet
35
    {
36
        $results = new ResultSet();
37
        foreach ($this->attributeRules as $attribute => $rules) {
38
            $results->addResult($attribute, $rules->validate($dataSet->getValue($attribute)));
39
        }
40
        return $results;
41
    }
42
43
    public function addRule(string $attribute, Rule $rule): self
44
    {
45
        if (!isset($this->attributeRules[$attribute])) {
46
            $this->attributeRules[$attribute] = new Rules();
47
        }
48
49
        $this->attributeRules[$attribute]->add($rule);
50
        return $this;
51
    }
52
}
53