Skip to content

Commit 26525b4

Browse files
committed
Add getErrorsAsArray method
1 parent c4f2492 commit 26525b4

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

src/Validation/ValidationResult.php

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,19 @@
1616
class ValidationResult implements JsonSerializable
1717
{
1818
/**
19-
* @var array
19+
* @var ValidationError[]
2020
*/
2121
protected $errors = [];
2222

2323
/**
2424
* @var string|null
2525
*/
26-
protected $message = null;
26+
protected $message;
2727

2828
/**
2929
* @var string|null
3030
*/
31-
protected $code = null;
31+
protected $code;
3232

3333
/**
3434
* Get all errors.
@@ -40,14 +40,30 @@ public function getErrors(): array
4040
return $this->errors;
4141
}
4242

43+
/**
44+
* Get all errors as array.
45+
*
46+
* @return array Errors
47+
*/
48+
public function getErrorsAsArray(): array
49+
{
50+
$result = [];
51+
52+
foreach ($this->errors as $error) {
53+
$result[] = $error->toArray();
54+
}
55+
56+
return $result;
57+
}
58+
4359
/**
4460
* Get first error.
4561
*
4662
* @return ValidationError|null Error message
4763
*/
4864
public function getFirstError()
4965
{
50-
return reset($this->errors);
66+
return reset($this->errors) ?: null;
5167
}
5268

5369
/**
@@ -138,10 +154,10 @@ public function clear()
138154
*/
139155
public function addError(string $field, string $message, string $code = null)
140156
{
141-
$message = new ValidationError($message);
142-
$message->setField($field)->setCode($code);
157+
$error = new ValidationError($message);
158+
$error->setField($field)->setCode($code);
143159

144-
$this->errors[] = $message;
160+
$this->errors[] = $error;
145161
}
146162

147163
/**
@@ -175,11 +191,8 @@ public function toArray(): array
175191
$result['message'] = $message;
176192
}
177193

178-
if (!empty($errors = $this->getErrors())) {
179-
$result['errors'] = [];
180-
foreach ($errors as $error) {
181-
$result['errors'][] = $error->toArray();
182-
}
194+
if ($errors = $this->getErrorsAsArray()) {
195+
$result['errors'] = $errors;
183196
}
184197

185198
return $result;

0 commit comments

Comments
 (0)