mirror of
https://github.com/flarum/framework.git
synced 2025-02-06 08:51:46 +08:00
Refactor JSON-API error formatter
This commit is contained in:
parent
e52a5d8353
commit
5048e097a5
|
@ -71,4 +71,9 @@ class HandledError
|
|||
{
|
||||
return $this->details;
|
||||
}
|
||||
|
||||
public function hasDetails(): bool
|
||||
{
|
||||
return ! empty($this->details);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,23 +27,37 @@ class JsonApiFormatter implements HttpFormatter
|
|||
{
|
||||
$document = new Document;
|
||||
|
||||
$data = [
|
||||
'status' => (string) $error->getStatusCode(),
|
||||
'code' => $error->getType(),
|
||||
];
|
||||
$details = $error->getDetails();
|
||||
|
||||
if (empty($details)) {
|
||||
$document->setErrors([$data]);
|
||||
if ($error->hasDetails()) {
|
||||
$document->setErrors($this->withDetails($error));
|
||||
} else {
|
||||
$document->setErrors(array_map(
|
||||
function ($row) use ($data) {
|
||||
return array_merge($data, $row);
|
||||
},
|
||||
$details
|
||||
));
|
||||
$document->setErrors($this->simple($error));
|
||||
}
|
||||
|
||||
return new JsonApiResponse($document, $error->getStatusCode());
|
||||
}
|
||||
|
||||
private function simple(HandledError $error): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'status' => (string) $error->getStatusCode(),
|
||||
'code' => $error->getType(),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private function withDetails(HandledError $error): array
|
||||
{
|
||||
$data = [
|
||||
'status' => (string) $error->getStatusCode(),
|
||||
'code' => $error->getType(),
|
||||
];
|
||||
|
||||
return array_map(
|
||||
function ($row) use ($data) {
|
||||
return array_merge($data, $row);
|
||||
},
|
||||
$error->getDetails()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user