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

Result   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 1 Features 1
Metric Value
eloc 21
dl 0
loc 63
ccs 24
cts 24
cp 1
rs 10
c 7
b 1
f 1
wmc 9

6 Methods

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