Passed
Pull Request — master (#147)
by Wilmer
02:49 queued 42s
created

FormErrors::clear()   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\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 370
    public function __construct(array $attributesErrors = [])
16
    {
17
        /** @psalm-var array<string, array<array-key, string>> */
18 370
        $this->attributesErrors = $attributesErrors;
19 370
    }
20
21 22
    public function addError(string $attribute, string $error): void
22
    {
23 22
        $this->attributesErrors[$attribute][] = $error;
24 22
    }
25
26 3
    public function getAllErrors(): array
27
    {
28 3
        return $this->attributesErrors;
29
    }
30
31 1
    public function getErrors(string $attribute): array
32
    {
33 1
        return $this->attributesErrors[$attribute] ?? [];
34
    }
35
36 3
    public function getErrorSummary(): array
37
    {
38 3
        return $this->renderErrorSumary($this->getAllErrors());
39
    }
40
41 4
    public function getErrorSummaryFirstErrors(): array
42
    {
43 4
        return $this->renderErrorSumary([$this->getFirstErrors()]);
44
    }
45
46 150
    public function getFirstError(string $attribute): string
47
    {
48 150
        if (empty($this->attributesErrors[$attribute])) {
49 139
            return '';
50
        }
51
52 19
        return reset($this->attributesErrors[$attribute]);
53
    }
54
55 4
    public function getFirstErrors(): array
56
    {
57 4
        if (empty($this->attributesErrors)) {
58 2
            return [];
59
        }
60
61 2
        $errors = [];
62
63 2
        foreach ($this->attributesErrors as $name => $es) {
64 2
            if (!empty($es)) {
65 2
                $errors[$name] = reset($es);
66
            }
67
        }
68
69 2
        return $errors;
70
    }
71
72 10
    public function hasErrors(?string $attribute = null): bool
73
    {
74 10
        return $attribute === null ? !empty($this->attributesErrors) : isset($this->attributesErrors[$attribute]);
75
    }
76
77 22
    public function clear(): void
78
    {
79 22
        $this->attributesErrors = [];
80 22
    }
81
82 4
    private function renderErrorSumary(array $errors): array
83
    {
84 4
        $lines = [];
85
86
        /** @var string[] errors */
87 4
        foreach ($errors as $error) {
88 4
            $lines = array_merge($lines, $error);
89
        }
90
91 4
        return $lines;
92
    }
93
}
94