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

Result::getErrorObjects()   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
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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>|null $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, function ($error) {
43
            /** @var Error $error */
44 31
            return $error->getMessage();
45 34
        });
46
    }
47
48 1
    public function getNestedErrors(string $separator = '.'): array
49
    {
50 1
        $valuePathCountMap = [];
51 1
        $errors = [];
52 1
        foreach ($this->errors as $error) {
53 1
            $stringValuePath = implode($separator, $error->getValuePath());
54 1
            $valuePathCount = $valuePathCountMap[$stringValuePath] ?? 0;
55 1
            $errorValuePath = "$stringValuePath.$valuePathCount";
56
57 1
            ArrayHelper::setValueByPath($errors, $errorValuePath, $error->getMessage());
58 1
            $valuePathCount++;
59 1
            $valuePathCountMap[$stringValuePath] = $valuePathCount;
60
        }
61
62 1
        return $errors;
63
    }
64
65 1
    public function getErrorsIndexedByPath(string $separator = '.'): array
66
    {
67 1
        $errors = [];
68 1
        foreach ($this->errors as $error) {
69 1
            $stringValuePath = implode($separator, $error->getValuePath());
70 1
            $errors[$stringValuePath][] = $error->getMessage();
71
        }
72
73 1
        return $errors;
74
    }
75
}
76