Passed
Pull Request — master (#104)
by
unknown
02:10
created

ResultSet::addResult()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
nc 4
nop 2
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 4
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use ArrayIterator;
8
use InvalidArgumentException;
9
use IteratorAggregate;
10
11
/**
12
 * ResultSet stores validation result of each attribute from {@link DataSetInterface}.
13
 * It is typically obtained by validating data set with {@link Validator}.
14
 */
15
final class ResultSet implements IteratorAggregate
16
{
17
    /**
18
     * @var Result[]
19
     */
20
    private array $results = [];
21
22 9
    public function addResult(
23
        string $attribute,
24
        Result $result
25
    ): void {
26 9
        if (!isset($this->results[$attribute])) {
27 9
            $this->results[$attribute] = $result;
28 9
            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 1
    }
37
38 6
    public function getResult(string $attribute): Result
39
    {
40 6
        if (!isset($this->results[$attribute])) {
41
            throw new InvalidArgumentException("There is no result for attribute \"$attribute\"");
42
        }
43
44 6
        return $this->results[$attribute];
45
    }
46
47 1
    public function getIterator(): ArrayIterator
48
    {
49 1
        return new ArrayIterator($this->results);
50
    }
51
52 1
    public function getErrors(): self
53
    {
54 1
        $resultSet = new self();
55 1
        foreach ($this->results as $attribute => $result) {
56 1
            if (!$result->isValid()) {
57 1
                $resultSet->addResult($attribute, $result);
58
            }
59
        }
60
61 1
        return $resultSet;
62
    }
63
64 2
    public function isValid(): bool
65
    {
66 2
        foreach ($this->results as $result) {
67 2
            if (!$result->isValid()) {
68 1
                return false;
69
            }
70
        }
71
72 1
        return true;
73
    }
74
}
75