ValidationContext::setError()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace App\Util;
4
5
/**
6
 * Class ValidationContext.
7
 */
8
class ValidationContext
9
{
10
    protected $message;
11
    protected $errors = [];
12
13
    /**
14
     * ValidationContext constructor.
15
     *
16
     * @param string $message
17
     */
18 7
    public function __construct(string $message = 'Please check your data')
19
    {
20 7
        $this->message = $message === 'Please check your data' ? 'Please check your data' : $message;
21 7
    }
22
23
    /**
24
     * Get message.
25
     *
26
     * @return null|string
27
     */
28 3
    public function getMessage()
29
    {
30 3
        return $this->message;
31
    }
32
33
    /**
34
     * Set message.
35
     *
36
     * @param string $message
37
     */
38 1
    public function setMessage(string $message)
39
    {
40 1
        $this->message = $message;
41 1
    }
42
43
    /**
44
     * Set error.
45
     *
46
     * @param string $field
47
     * @param string $message
48
     */
49 5
    public function setError(string $field, string $message)
50
    {
51 5
        $this->errors[] = [
52 5
            'field' => $field,
53 5
            'message' => $message,
54
        ];
55 5
    }
56
57
    /**
58
     * Get errors.
59
     *
60
     * @return array $errors
61
     */
62 2
    public function getErrors()
63
    {
64 2
        return $this->errors;
65
    }
66
67
    /**
68
     * Fail.
69
     *
70
     * Check if there are any errors
71
     *
72
     * @return bool
73
     */
74 1
    public function fails()
75
    {
76 1
        return !empty($this->errors);
77
    }
78
79
    /**
80
     * Success.
81
     *
82
     * Check if there are not any errors.
83
     *
84
     * @return bool
85
     */
86 1
    public function success()
87
    {
88 1
        return empty($this->errors);
89
    }
90
91
    /**
92
     * Clear.
93
     *
94
     * Clear message and errors
95
     */
96 1
    public function clear()
97
    {
98 1
        $this->message = null;
99 1
        $this->errors = [];
100 1
    }
101
102
    /**
103
     * Validation To Array.
104
     *
105
     * Get Validation Context as array
106
     *
107
     * @return array $result
108
     */
109 1
    public function toArray()
110
    {
111
        $result = [
112 1
            'message' => $this->message,
113 1
            'errors' => $this->errors,
114
        ];
115
116 1
        return $result;
117
    }
118
}
119