Test Failed
Pull Request — master (#147)
by Wilmer
02:42
created

FormErrors::renderErrorSumary()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form;
6
7
/**
8
 * FormErrors represents a form validation errors collection.
9
 */
10
final class FormErrors implements FormErrorsInterface
11
{
12
    /** @psalm-var array<string, array<array-key, string>> */
13
    private array $attributesErrors;
14
15
    public function __construct(array $attributesErrors = [])
16
    {
17
        /** @psalm-var array<string, array<array-key, string>> */
18
        $this->attributesErrors = $attributesErrors;
19
    }
20
21
    public function addError(string $attribute, string $error): void
22
    {
23
        $this->attributesErrors[$attribute][] = $error;
24
    }
25
26
    public function getAllErrors(): array
27
    {
28
        return $this->attributesErrors;
29
    }
30
31
    public function getErrors(string $attribute): array
32
    {
33
        return $this->attributesErrors[$attribute] ?? [];
34
    }
35
36
    public function getErrorSummary(): array
37
    {
38
        return $this->renderErrorSumary($this->getAllErrors());
39
    }
40
41
    public function getErrorSummaryFirstErrors(): array
42
    {
43
        return $this->renderErrorSumary([$this->getFirstErrors()]);
44
    }
45
46
    public function getFirstError(string $attribute): string
47
    {
48
        if (empty($this->attributesErrors[$attribute])) {
49
            return '';
50
        }
51
52
        return reset($this->attributesErrors[$attribute]);
53
    }
54
55
    public function getFirstErrors(): array
56
    {
57
        if (empty($this->attributesErrors)) {
58
            return [];
59
        }
60
61
        $errors = [];
62
63
        foreach ($this->attributesErrors as $name => $es) {
64
            if (!empty($es)) {
65
                $errors[$name] = reset($es);
66
            }
67
        }
68
69
        return $errors;
70
    }
71
72
    public function hasErrors(?string $attribute = null): bool
73
    {
74
        return $attribute === null ? !empty($this->attributesErrors) : isset($this->attributesErrors[$attribute]);
75
    }
76
77
    public function clear(): void
78
    {
79
        $this->attributesErrors = [];
80
    }
81
82
    private function renderErrorSumary(array $errors): array
83
    {
84
        $lines = [];
85
86
        /** @var string[] errors */
87
        foreach ($errors as $error) {
88
            $lines = array_merge($lines, $error);
89
        }
90
91
        return $lines;
92
    }
93
}
94