Test Failed
Pull Request — master (#151)
by
unknown
02:01
created

Result::getNestedErrors()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 0
dl 0
loc 15
ccs 0
cts 0
cp 0
crap 6
rs 9.9332
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 157
    private array $errors = [];
15
16 157
    public function isValid(): bool
17
    {
18
        return $this->errors === [];
19 127
    }
20
21 127
    /**
22 127
     * @psalm-param list<int|string>|null $valuePath
23
     */
24
    public function addError(string $message, array $valuePath = []): void
25
    {
26
        $this->errors[] = new Error($message, $valuePath);
27 35
    }
28
29 35
    /**
30
     * @return Error[]
31
     */
32
    public function getErrorObjects(): array
33
    {
34
        return $this->errors;
35
    }
36
37
    /**
38
     * @return string[]
39
     */
40
    public function getErrors(): array
41
    {
42
        return ArrayHelper::getColumn($this->errors, function ($error) {
43
            /** @var Error $error */
44
            return $error->getMessage();
45
        });
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function getNestedErrors(): array
52
    {
53
        $valuePathCountMap = [];
54
        $errors = [];
55
        foreach ($this->errors as $error) {
56
            $stringValuePath = $error->getStringValuePath();
57
            $valuePathCount = $valuePathCountMap[$stringValuePath] ?? 0;
58
            $errorValuePath = "$stringValuePath.$valuePathCount";
59
60
            ArrayHelper::setValueByPath($errors, $errorValuePath, $error->getMessage());
61
            $valuePathCount++;
62
            $valuePathCountMap[$stringValuePath] = $valuePathCount;
63
        }
64
65
        return $errors;
66
    }
67
68
    /**
69
     * @return array
70
     */
71
    public function getFlatDetailedErrors(): array
72
    {
73
        $errors = [];
74
        foreach ($this->errors as $error) {
75
            $errors[$error->getStringValuePath()][] = $error->getMessage();
76
        }
77
78
        return $errors;
79
    }
80
}
81