Skip to content

Instantly share code, notes, and snippets.

@ternavsky
Last active June 25, 2018 14:40
Show Gist options
  • Save ternavsky/56dd62a712c41aa6860c24728a5f58e0 to your computer and use it in GitHub Desktop.
Save ternavsky/56dd62a712c41aa6860c24728a5f58e0 to your computer and use it in GitHub Desktop.
Base class for Laravel Api controller
<?php
use Backend\Classes\Controller;
use Illuminate\Http\Response;
class ApiController extends Controller {
protected $statusCode = Response::HTTP_OK;
public function setStatusCode($code)
{
$this->statusCode = $code;
return $this;
}
public function respondNotFound(ApiError $error)
{
return $this->setStatusCode(Response::HTTP_NOT_FOUND)->respondError($error);
}
public function respondInternalError(ApiError $error)
{
return $this->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR)->respondError($error);
}
protected function respond($data, $headers = [])
{
return response()->json($data, $this->statusCode, $headers);
}
public function respondValidationError(ApiError $error)
{
return $this->setStatusCode(Response::HTTP_NOT_ACCEPTABLE)->respondError($error);
}
public function respondUnauthorizedError(ApiError $error)
{
return $this->setStatusCode(Response::HTTP_UNAUTHORIZED)->respondError($error);
}
public function respondSuccess($data = [])
{
return $this->respond([
'success' => true,
'error' => null,
'data' => $data
]);
}
public function respondError(ApiError $error)
{
return $this->respond([
'success' => false,
'error' => [
'code' => $error->getCode(),
'message' => $error->getMessage()
]
]);
}
}
<?php namespace Progforce\Dermadetect\Api;
class ApiError {
protected $code;
protected $message;
const ERROR_TYPES = [
'token_absent' => [
'code' => 101,
'message' => 'Token was not provided'
],
// ...
];
public function __construct($code, $message)
{
$this->code = $code;
$this->message = $message;
}
public function setMessage($msg)
{
$this->message = $msg;
}
public function getMessage()
{
return $this->message;
}
public function getCode()
{
return $this->code;
}
public static function create($type, $msg = null)
{
$errorData = self::ERROR_TYPES[$type];
$error = new static($errorData['code'], $msg ? $msg : $errorData['message']);
return $error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment