41 lines
1.3 KiB
PHP
41 lines
1.3 KiB
PHP
<?php
|
|
namespace Incoviba\Controller\API;
|
|
|
|
use Throwable;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
|
|
trait withJson
|
|
{
|
|
public function withJson(ResponseInterface $response, array|object $data = [], int $statusCode = 200): ResponseInterface
|
|
{
|
|
$response->getBody()->write(json_encode($data));
|
|
return $response->withStatus($statusCode)->withHeader('Content-Type', 'application/json');
|
|
}
|
|
public function parseError(Throwable $exception): array
|
|
{
|
|
return [
|
|
'code' => $exception->getCode(),
|
|
'message' => $exception->getMessage(),
|
|
'file' => $exception->getFile(),
|
|
'line' => $exception->getLine(),
|
|
'trace' => $exception->getTraceAsString()
|
|
];
|
|
}
|
|
public function withError(ResponseInterface $response, Throwable $exception): ResponseInterface
|
|
{
|
|
$output = $this->parseError($exception);
|
|
|
|
$response->getBody()->write(json_encode(['error' => $output]));
|
|
return $response->withHeader('Content-Type', 'application/json');
|
|
}
|
|
public function withErrors(ResponseInterface $response, array $errors): ResponseInterface
|
|
{
|
|
foreach ($errors as $error) {
|
|
$response = $this->withError($response, $error);
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
}
|