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

Result   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 1 Features 1
Metric Value
eloc 22
dl 0
loc 65
ccs 28
cts 28
cp 1
rs 10
c 5
b 1
f 1
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 3 1
A getErrors() 0 5 1
A getErrorObjects() 0 3 1
A addError() 0 3 1
A getNestedErrors() 0 15 2
A getErrorsIndexedByPath() 0 9 2
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