@@ -13,6 +13,9 @@ class ApiResponse extends Response {
13
13
// Holds the optional error message (in case of a 'error')
14
14
protected $ errorMessage ;
15
15
16
+ // Hold the data
17
+ protected $ data ;
18
+
16
19
17
20
/**
18
21
* Sends content for the current web response.
@@ -41,21 +44,27 @@ public function formatToJsend(){
41
44
// Create an empty response
42
45
$ response = null ;
43
46
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
+
44
53
// If response is successful
45
54
if ($ this ->isSuccessful ()){
46
55
$ response = [
47
56
'status ' => 'success ' ,
48
- 'data ' => $ this -> getOriginalContent () ,
57
+ 'data ' => $ response_data ,
49
58
];
50
59
51
- // If reponse is a client error
60
+ // If reponse is a client error
52
61
}elseif ($ this ->isClientError ()){
53
62
$ response = [
54
63
'status ' => 'fail ' ,
55
- 'data ' => $ this -> getOriginalContent () ,
64
+ 'data ' => $ response_data ,
56
65
];
57
66
58
- // If response is a server error
67
+ // If response is a server error
59
68
}elseif ($ this ->isServerError ()){
60
69
$ response = [
61
70
'status ' => 'error ' ,
@@ -69,7 +78,7 @@ public function formatToJsend(){
69
78
70
79
// Optional data
71
80
if ($ this ->getOriginalContent ()){
72
- $ response ['data ' ] = $ this -> getOriginalContent () ;
81
+ $ response ['data ' ] = $ response_data ;
73
82
}
74
83
75
84
}
@@ -96,4 +105,17 @@ public function setErrorMessage($errorMessage){
96
105
97
106
return $ this ;
98
107
}
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
+ }
99
121
}
0 commit comments