Passed
Pull Request — master (#81)
by Def
01:31
created

Validator   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Test Coverage

Coverage 95.83%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 66
ccs 23
cts 24
cp 0.9583
rs 10
c 0
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 5
A asArray() 0 7 2
A validate() 0 10 2
A addRule() 0 6 2
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
    /**
13
     * @var Rules[]
14
     */
15
    private array $attributeRules = [];
16
17 5
    public function __construct(iterable $rules = [])
18
    {
19 5
        foreach ($rules as $attribute => $ruleSets) {
20 4
            if ($ruleSets instanceof Rule) {
21 1
                $ruleSets = [$ruleSets];
22 4
            } elseif (!is_iterable($ruleSets)) {
23
                throw new \InvalidArgumentException('Rules should be either instance of Rule class or a array of instances of Rule class');
24
            }
25 4
            foreach ($ruleSets as $rule) {
26 4
                $this->addRule($attribute, $rule);
27
            }
28
        }
29
    }
30
31 4
    public function validate(DataSetInterface $dataSet): ResultSet
32
    {
33 4
        $results = new ResultSet();
34 4
        foreach ($this->attributeRules as $attribute => $rules) {
35 4
            $results->addResult(
36 4
                $attribute,
37 4
                $rules->validate($dataSet->getAttributeValue($attribute), $dataSet)
38
            );
39
        }
40 4
        return $results;
41
    }
42
43
    /**
44
     * @param string $attribute
45
     * @param Rule|callable
46
     */
47 5
    public function addRule(string $attribute, $rule): void
48
    {
49 5
        if (!isset($this->attributeRules[$attribute])) {
50 5
            $this->attributeRules[$attribute] = new Rules([]);
51
        }
52 5
        $this->attributeRules[$attribute]->add($rule);
53
    }
54
55
    /**
56
     * Return rules for attributes as array.
57
     * For example:
58
     * [
59
     *    'amount' => [
60
     *      ['number', 'integer' => true, 'max' => 100, 'notANumberMessage' => 'Value must be an integer.',
61
     *          'tooBigMessage' => 'Value must be no greater than 100.'],
62
     *      ['callback'],
63
     *    ],
64
     *    'name' => ['hasLength', 'max' => 20, 'message' => 'This value must be a string.',
65
     *      'This value should contain at most 20 characters.'],
66
     * ]
67
     * @return array
68
     */
69 1
    public function asArray(): array
70
    {
71 1
        $rulesOfArray = [];
72 1
        foreach ($this->attributeRules as $attribute => $rules) {
73 1
            $rulesOfArray[$attribute] = $rules->asArray();
74
        }
75 1
        return $rulesOfArray;
76
    }
77
}
78