Created
December 6, 2021 12:59
-
-
Save Sekaiichi/35be95beb9ae6d3bcf4ee1b758654385 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Contracts\Validation\Validator; | |
use Illuminate\Http\JsonResponse; | |
use Illuminate\Http\Request; | |
use Illuminate\Http\Resources\Json\JsonResource; | |
use Illuminate\Http\Response; | |
use Illuminate\Pagination\LengthAwarePaginator; | |
trait ApiResponse | |
{ | |
protected int $statusCode = 200; | |
protected string $message = ''; | |
protected bool $error = false; | |
protected array $debugInfo = []; | |
protected int $errorCode = 0; | |
public function getPaginationLimit() | |
{ | |
return min(intval(request()->get('limit', 10)), self::DEFAULT_MAX_LIMIT); | |
} | |
public function successResponse($data, $statusCode = Response::HTTP_OK): JsonResponse | |
{ | |
return response()->json(['data' => $data], $statusCode); | |
} | |
public function errorResponse($errorMessage, $statusCode): JsonResponse | |
{ | |
return response()->json(['error' => $errorMessage, 'error_code' => $statusCode], $statusCode); | |
} | |
/** | |
* Function to return an error response. | |
* | |
* @param $message | |
* @return mixed | |
*/ | |
public function respondWithError($message): JsonResponse | |
{ | |
$this->error = true; | |
$this->message = $message; | |
return $this->respond(array()); | |
} | |
public function respondValidationsError(array $data, int $statusCode = Response::HTTP_UNPROCESSABLE_ENTITY, $message = 'Validation error'): JsonResponse | |
{ | |
$this->error = true; | |
$this->message = $message; | |
$this->statusCode = $statusCode; | |
return $this->respond($data); | |
} | |
/** | |
* Function to return an unauthorized response. | |
* | |
* @param string $message | |
* @return mixed | |
*/ | |
public function respondUnauthorizedError(string $message = 'Unauthorized!') | |
{ | |
$this->statusCode = Response::HTTP_UNAUTHORIZED; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Function to return a bad request response. | |
* | |
* @param string $message | |
* @return mixed | |
*/ | |
public function respondBadRequestError(string $message = 'Bad Request!') | |
{ | |
$this->statusCode = Response::HTTP_BAD_REQUEST; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Function to return forbidden error response. | |
* | |
* @param string $message | |
* | |
* @return mixed | |
*/ | |
public function respondForbiddenError(string $message = 'Permission denied!') | |
{ | |
$this->statusCode = Response::HTTP_FORBIDDEN; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Function to return a Not Found response. | |
* | |
* @param string $message | |
* @return mixed | |
*/ | |
public function respondNotFound(string $message = 'Resource Not Found') | |
{ | |
$this->statusCode = Response::HTTP_NOT_FOUND; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Function to return an internal error response. | |
* | |
* @param string $message | |
* @return mixed | |
*/ | |
public function respondInternalError(string $message = 'Internal Server Error!') | |
{ | |
$this->statusCode = Response::HTTP_INTERNAL_SERVER_ERROR; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Function to return an internal error response. | |
* | |
* @param string $message | |
* @return mixed | |
*/ | |
public function respondMethodNotAllowed(string $message = 'Method not allowed!') | |
{ | |
$this->statusCode = Response::HTTP_METHOD_NOT_ALLOWED; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Function to return a service unavailable response. | |
* | |
* @param string $message | |
* @return mixed | |
*/ | |
public function respondServiceUnavailable(string $message = "Service Unavailable!") | |
{ | |
$this->statusCode = Response::HTTP_SERVICE_UNAVAILABLE; | |
return $this->respondWithError($message); | |
} | |
/** | |
* Throws a bad request exception with the validator's error messages. | |
* | |
* @param Validator $validator The validator to get the message from | |
* | |
* @return mixed | |
*/ | |
public function showValidationError(Validator $validator) | |
{ | |
$this->error = true; | |
$this->statusCode = Response::HTTP_BAD_REQUEST; | |
$this->message = implode("|", $validator->errors()->all()); | |
return $this->respond(); | |
} | |
/** | |
* Function to return a created response | |
* | |
* @param $data | |
* @return JsonResponse | |
*/ | |
public function respondCreated($data): JsonResponse | |
{ | |
$this->statusCode = Response::HTTP_CREATED; | |
return $this->respond($data); | |
} | |
/** | |
* Function to return a response with a message | |
* | |
* @param $data array The data to be included | |
* | |
* @param $message string The message to be shown in the meta of the response | |
* | |
* @return mixed | |
*/ | |
public function respondWithMessage($data, string $message) | |
{ | |
$this->statusCode = Response::HTTP_OK; | |
$this->message = $message; | |
return $this->respond($data); | |
} | |
/** | |
* Function to return a generic response. | |
* | |
* @param $data array to be used in response. | |
* @param array $headers Headers to b used in response. | |
* @return JsonResponse | |
*/ | |
public function respond($data = [], array $headers = []): JsonResponse | |
{ | |
$meta = [ | |
'meta' => [ | |
'error' => $this->error, | |
'message' => $this->message, | |
'statusCode' => $this->statusCode, | |
], | |
]; | |
if (app()->environment() === 'local') { | |
$meta['_debug'] = app('debugbar')->getData(); | |
} | |
$data = array_merge($meta, ['response' => $data]); | |
return response()->json($data, $this->statusCode, $headers); | |
} | |
/** | |
* Returns a LengthAwarePaginator for an array collection | |
* | |
* @param Request $request | |
* @param array $items | |
* @return LengthAwarePaginator | |
*/ | |
public function paginate(Request $request, $items): LengthAwarePaginator | |
{ | |
$items = $items['data'] ?? $items; | |
$limit = min((int)$request->get('limit', 10), 1000); | |
$page = (int)$request->get('page', 1); | |
$offset = ($page-1) * $limit; | |
return new LengthAwarePaginator(array_slice($items, $offset, $limit), count($items), $limit, $page); | |
} | |
/** | |
* Responds paginated items | |
* | |
* @param LengthAwarePaginator $awarePaginator | |
* @param JsonResource|null $resourceForMap | |
* @return JsonResponse | |
*/ | |
public function respondPagination(LengthAwarePaginator $awarePaginator, JsonResource $resourceForMap = null): JsonResponse | |
{ | |
if (!is_null($resourceForMap)) { | |
$items = $resourceForMap->collection($awarePaginator->items()); | |
} else { | |
$items = $awarePaginator->items(); | |
} | |
return $this->respond([ | |
'pagination' => $this->getPagination($awarePaginator), | |
'items' => $items, | |
]); | |
} | |
/** | |
* Retrieves the pagination meta in an array format | |
* | |
* @param LengthAwarePaginator $item | |
* @return array | |
*/ | |
public function getPagination(LengthAwarePaginator $item): array | |
{ | |
return [ | |
'total' => $item->total(), | |
'current_page' => $item->currentPage(), | |
'last_page' => $item->lastPage(), | |
'from' => $item->firstItem(), | |
'to' => $item->lastItem() | |
]; | |
} | |
public function successJson($message = '', $data = null): JsonResponse | |
{ | |
return response()->json([ | |
'error' => false, | |
'message' => $message, | |
'data' => $data | |
]); | |
} | |
public function errorJson($message, $data = null): JsonResponse | |
{ | |
return response()->json([ | |
'error' => true, | |
'message' => $message, | |
'data' => $data | |
]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment