Passed
Pull Request — master (#55)
by Alexander
01:33
created

ResultSet   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 72.21%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 44
ccs 13
cts 18
cp 0.7221
rs 10
c 1
b 0
f 0
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A addResult() 0 16 6
A getIterator() 0 3 1
A getResult() 0 7 2
A hasErrors() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
/**
8
 * ResultSet stores validation result of each attribute from {@link DataSetInterface}.
9
 * It is typically obtained by validating data set with {@link Validator}.
10
 */
11
final class ResultSet implements \IteratorAggregate
12
{
13
    /**
14
     * @var Result[]
15
     */
16
    private array $results = [];
17
    private bool $hasErrors = false;
18
19 4
    public function addResult(
20
        string $attribute,
21
        Result $result
22
    ): void {
23 4
        if ($this->hasErrors === false && $result->isValid() === false) {
24 4
            $this->hasErrors = true;
25
        }
26 4
        if (!isset($this->results[$attribute])) {
27 4
            $this->results[$attribute] = $result;
28 4
            return;
29
        }
30 2
        if ($result->isValid()) {
31 1
            return;
32
        }
33 1
        foreach ($result->getErrors() as $error) {
34 1
            $this->results[$attribute]->addError($error);
35
        }
36
    }
37
38
    public function hasErrors(): bool
39
    {
40
        return $this->hasErrors;
41
    }
42
43 4
    public function getResult(string $attribute): Result
44
    {
45 4
        if (!isset($this->results[$attribute])) {
46
            throw new \InvalidArgumentException("There is no result for attribute \"$attribute\"");
47
        }
48
49 4
        return $this->results[$attribute];
50
    }
51
52
    public function getIterator()
53
    {
54
        return new \ArrayIterator($this->results);
55
    }
56
}
57