Skip to content

Commit

Permalink
update for Laravel 7+
Browse files Browse the repository at this point in the history
  • Loading branch information
JordyAlkema committed Oct 30, 2020
1 parent 8d3323a commit 9bdf03c
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/ApiResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ class ApiResponse extends Response {
// Holds the optional error message (in case of a 'error')
protected $errorMessage;

// Hold the data
protected $data;


/**
* Sends content for the current web response.
Expand Down Expand Up @@ -41,21 +44,27 @@ public function formatToJsend(){
// Create an empty response
$response = null;

if (method_exists($this->data, '__toString') || is_scalar($this->data)){
$response_data = $this->data;
}else{
$response_data = json_encode($this->data);
}

// If response is successful
if($this->isSuccessful()){
$response = [
'status' => 'success',
'data' => $this->getOriginalContent(),
'data' => $response_data,
];

// If reponse is a client error
// If reponse is a client error
}elseif ($this->isClientError()){
$response = [
'status' => 'fail',
'data' => $this->getOriginalContent(),
'data' => $response_data,
];

// If response is a server error
// If response is a server error
}elseif ($this->isServerError()){
$response = [
'status' => 'error',
Expand All @@ -69,7 +78,7 @@ public function formatToJsend(){

// Optional data
if($this->getOriginalContent()){
$response['data'] = $this->getOriginalContent();
$response['data'] = $response_data;
}

}
Expand All @@ -96,4 +105,17 @@ public function setErrorMessage($errorMessage){

return $this;
}

/**
* @param string|null $content
* @param int $status
* @param array $headers
* @return ApiResponse|void
*/
public static function create($content = '', int $status = 200, array $headers = []){
$response = new ApiResponse($content, $status, $headers);
$response->data = $content;

return $response;
}
}

0 comments on commit 9bdf03c

Please sign in to comment.