Refactor JSON-API error formatter

This commit is contained in:
Franz Liedke 2019-09-04 23:30:22 +02:00
parent e52a5d8353
commit 5048e097a5
2 changed files with 33 additions and 14 deletions

View File

@ -71,4 +71,9 @@ class HandledError
{ {
return $this->details; return $this->details;
} }
public function hasDetails(): bool
{
return ! empty($this->details);
}
} }

View File

@ -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()
);
}
} }