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

ResultSet::getResult()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 10
c 0
b 0
f 0
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