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

Result::isValid()   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 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