Last active
June 25, 2018 14:40
-
-
Save ternavsky/56dd62a712c41aa6860c24728a5f58e0 to your computer and use it in GitHub Desktop.
Base class for Laravel Api controller
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 | |
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() | |
] | |
]); | |
} | |
} |
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 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