Skip to content

Commit 9bdf03c

Browse files
committed
update for Laravel 7+
1 parent 8d3323a commit 9bdf03c

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

src/ApiResponse.php

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ class ApiResponse extends Response {
1313
// Holds the optional error message (in case of a 'error')
1414
protected $errorMessage;
1515

16+
// Hold the data
17+
protected $data;
18+
1619

1720
/**
1821
* Sends content for the current web response.
@@ -41,21 +44,27 @@ public function formatToJsend(){
4144
// Create an empty response
4245
$response = null;
4346

47+
if (method_exists($this->data, '__toString') || is_scalar($this->data)){
48+
$response_data = $this->data;
49+
}else{
50+
$response_data = json_encode($this->data);
51+
}
52+
4453
// If response is successful
4554
if($this->isSuccessful()){
4655
$response = [
4756
'status' => 'success',
48-
'data' => $this->getOriginalContent(),
57+
'data' => $response_data,
4958
];
5059

51-
// If reponse is a client error
60+
// If reponse is a client error
5261
}elseif ($this->isClientError()){
5362
$response = [
5463
'status' => 'fail',
55-
'data' => $this->getOriginalContent(),
64+
'data' => $response_data,
5665
];
5766

58-
// If response is a server error
67+
// If response is a server error
5968
}elseif ($this->isServerError()){
6069
$response = [
6170
'status' => 'error',
@@ -69,7 +78,7 @@ public function formatToJsend(){
6978

7079
// Optional data
7180
if($this->getOriginalContent()){
72-
$response['data'] = $this->getOriginalContent();
81+
$response['data'] = $response_data;
7382
}
7483

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

97106
return $this;
98107
}
108+
109+
/**
110+
* @param string|null $content
111+
* @param int $status
112+
* @param array $headers
113+
* @return ApiResponse|void
114+
*/
115+
public static function create($content = '', int $status = 200, array $headers = []){
116+
$response = new ApiResponse($content, $status, $headers);
117+
$response->data = $content;
118+
119+
return $response;
120+
}
99121
}

0 commit comments

Comments
 (0)