TraitErrors::getFirstErrors()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace WebComplete\form;
4
5
trait TraitErrors
6
{
7
8
    protected $errors = [];
9
10
    /**
11
     * @param string $field
12
     */
13
    public function resetErrors($field = null)
14
    {
15
        if ($field !== null && $field) {
16
            unset($this->errors[$field]);
17
        } else {
18
            $this->errors = [];
19
        }
20
    }
21
22
    /**
23
     * @param $field
24
     * @param $error
25
     */
26
    public function addError($field, $error)
27
    {
28
        if (!isset($this->errors[$field])) {
29
            $this->errors[$field] = [];
30
        }
31
        $this->errors[$field][] = $error;
32
    }
33
34
    /**
35
     * @param string|null $field
36
     *
37
     * @return bool
38
     */
39
    public function hasErrors($field = null): bool
40
    {
41
        return \count($this->getErrors($field)) > 0;
42
    }
43
44
    /**
45
     * @param string|null $field
46
     *
47
     * @return array
48
     */
49
    public function getErrors($field = null): array
50
    {
51
        if ($field !== null && $field) {
52
            return $this->errors[$field] ?? [];
53
        }
54
55
        return $this->errors;
56
    }
57
58
    /**
59
     * @return array
60
     */
61
    public function getFirstErrors(): array
62
    {
63
        $result = [];
64
        foreach ($this->getErrors() as $field => $errors) {
65
            if ($errors) {
66
                $result[$field] = \reset($errors);
67
            }
68
        }
69
70
        return $result;
71
    }
72
73
    /**
74
     * @param $field
75
     *
76
     * @return string|null
77
     */
78
    public function getFirstError($field)
79
    {
80
        return isset($this->errors[$field]) && $this->errors[$field] ? \reset($this->errors[$field]) : null;
81
    }
82
}
83