Passed
Pull Request — master (#54)
by
unknown
01:37
created

ResultSet::hasErrors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
cc 1
rs 10
ccs 2
cts 2
cp 1
crap 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 5
    public function addResult(
20
        string $attribute,
21
        Result $result
22
    ): void {
23 5
        if ($this->hasErrors === false && $result->isValid() === false) {
24 5
            $this->hasErrors = true;
25
        }
26 5
        if (!isset($this->results[$attribute])) {
27 5
            $this->results[$attribute] = $result;
28 5
            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 1
    public function hasErrors(): bool
39
    {
40 1
        return $this->hasErrors;
41
    }
42
43 5
    public function getResult(string $attribute): Result
44
    {
45 5
        if (!isset($this->results[$attribute])) {
46
            throw new \InvalidArgumentException("There is no result for attribute \"$attribute\"");
47
        }
48
49 5
        return $this->results[$attribute];
50
    }
51
52
    public function getIterator()
53
    {
54
        return new \ArrayIterator($this->results);
55
    }
56
}
57