|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Form; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* FormErrors represents a form 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
|
1 |
|
public function getError(string $attribute): array |
|
27
|
|
|
{ |
|
28
|
1 |
|
return $this->attributesErrors[$attribute] ?? []; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
3 |
|
public function getErrors(): array |
|
32
|
|
|
{ |
|
33
|
3 |
|
return $this->attributesErrors; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
4 |
|
public function getErrorSummary(bool $showAllErrors): array |
|
37
|
|
|
{ |
|
38
|
4 |
|
$lines = []; |
|
39
|
4 |
|
$errors = $showAllErrors ? $this->getErrors() : [$this->getFirstErrors()]; |
|
40
|
|
|
|
|
41
|
4 |
|
foreach ($errors as $error) { |
|
42
|
3 |
|
$lines = array_merge($lines, $error); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
return $lines; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
150 |
|
public function getFirstError(string $attribute): string |
|
49
|
|
|
{ |
|
50
|
150 |
|
if (empty($this->attributesErrors[$attribute])) { |
|
51
|
139 |
|
return ''; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
19 |
|
return reset($this->attributesErrors[$attribute]); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
2 |
|
public function getFirstErrors(): array |
|
58
|
|
|
{ |
|
59
|
2 |
|
if (empty($this->attributesErrors)) { |
|
60
|
1 |
|
return []; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
1 |
|
$errors = []; |
|
64
|
|
|
|
|
65
|
1 |
|
foreach ($this->attributesErrors as $name => $es) { |
|
66
|
1 |
|
if (!empty($es)) { |
|
67
|
1 |
|
$errors[$name] = reset($es); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
1 |
|
return $errors; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
10 |
|
public function hasErrors(?string $attribute = null): bool |
|
75
|
|
|
{ |
|
76
|
10 |
|
return $attribute === null ? !empty($this->attributesErrors) : isset($this->attributesErrors[$attribute]); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
22 |
|
public function clear(): void |
|
80
|
|
|
{ |
|
81
|
22 |
|
$this->attributesErrors = []; |
|
82
|
22 |
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|