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

ResultSet::addResult()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
nc 4
nop 2
dl 0
loc 16
ccs 10
cts 10
cp 1
crap 4
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Validator;
4
5
/**
6
 * ResultSet stores validation result of each attribute from {@link DataSetInterface}.
7
 * It is typically obtained by validating data set with {@link Validator}.
8
 */
9
final class ResultSet implements \IteratorAggregate
10
{
11
    /**
12
     * @var Result[]
13
     */
14
    private array $results = [];
15
16 2
    public function addResult(string $attribute, Result $result): self
17
    {
18 2
        $new = clone $this;
19
20 2
        if (!isset($new->results[$attribute])) {
21 2
            $new->results[$attribute] = $result;
22 2
            return $new;
23
        }
24 2
        if ($result->isValid()) {
25 1
            return $new;
26
        }
27 1
        foreach ($result->getErrors() as $error) {
28 1
            $new->results[$attribute] = $new->results[$attribute]->addError($error);
29
        }
30
31 1
        return $new;
32
    }
33
34 2
    public function getResult(string $attribute): Result
35
    {
36 2
        if (!isset($this->results[$attribute])) {
37
            throw new \InvalidArgumentException("There is no result for attribute \"$attribute\"");
38
        }
39
40 2
        return $this->results[$attribute];
41
    }
42
43
    public function getIterator()
44
    {
45
        return new \ArrayIterator($this->results);
46
    }
47
}
48