mirror of
https://github.com/flarum/framework.git
synced 2025-02-06 11:51:45 +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;
|
return $this->details;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function hasDetails(): bool
|
||||||
|
{
|
||||||
|
return ! empty($this->details);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -27,23 +27,37 @@ class JsonApiFormatter implements HttpFormatter
|
||||||
{
|
{
|
||||||
$document = new Document;
|
$document = new Document;
|
||||||
|
|
||||||
$data = [
|
if ($error->hasDetails()) {
|
||||||
'status' => (string) $error->getStatusCode(),
|
$document->setErrors($this->withDetails($error));
|
||||||
'code' => $error->getType(),
|
|
||||||
];
|
|
||||||
$details = $error->getDetails();
|
|
||||||
|
|
||||||
if (empty($details)) {
|
|
||||||
$document->setErrors([$data]);
|
|
||||||
} else {
|
} else {
|
||||||
$document->setErrors(array_map(
|
$document->setErrors($this->simple($error));
|
||||||
function ($row) use ($data) {
|
|
||||||
return array_merge($data, $row);
|
|
||||||
},
|
|
||||||
$details
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return new JsonApiResponse($document, $error->getStatusCode());
|
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