Passed
Pull Request — master (#151)
by
unknown
02:12
created

Result::getErrors()   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
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\Arrays\ArrayHelper;
8
9
final class Result
10
{
11
    /**
12
     * @var Error[]
13
     */
14
    private array $errors = [];
15
16 159
    public function isValid(): bool
17
    {
18 159
        return $this->errors === [];
19
    }
20
21
    /**
22
     * @psalm-param list<int|string> $valuePath
23
     */
24 129
    public function addError(string $message, array $valuePath = []): void
25
    {
26 129
        $this->errors[] = new Error($message, $valuePath);
27 129
    }
28
29
    /**
30
     * @return Error[]
31
     */
32 17
    public function getErrorObjects(): array
33
    {
34 17
        return $this->errors;
35
    }
36
37
    /**
38
     * @return string[]
39
     */
40 34
    public function getErrors(): array
41
    {
42 34
        return ArrayHelper::getColumn($this->errors, static fn (Error $error) => $error->getMessage());
43
    }
44
45 1
    public function getNestedErrors(): array
46
    {
47 1
        $nestedErrors = [];
48 1
        foreach ($this->errors as $error) {
49 1
            $valuePath = $error->getValuePath();
50 1
            if ($valuePath === []) {
51
                $nestedErrors[0][] = $error->getMessage();
52
            } else {
53 1
                $errors = ArrayHelper::getValue($nestedErrors, $valuePath, []);
54 1
                $errors[] = $error->getMessage();
55
56 1
                ArrayHelper::setValue($nestedErrors, $valuePath, $errors);
57
            }
58
        }
59
60 1
        return $nestedErrors;
61
    }
62
63 1
    public function getErrorsIndexedByPath(string $separator = '.'): array
64
    {
65 1
        $errors = [];
66 1
        foreach ($this->errors as $error) {
67 1
            $stringValuePath = implode($separator, $error->getValuePath());
68 1
            $errors[$stringValuePath][] = $error->getMessage();
69
        }
70
71 1
        return $errors;
72
    }
73
}
74