Skip to content

Commit bdf2c89

Browse files
committed
Add json() for Response and integrate to Controller
1 parent f1592a2 commit bdf2c89

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

src/http/Response.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,4 +179,24 @@ public static function jsonFormat($data)
179179
{
180180
return json_encode($data);
181181
}
182+
183+
/**
184+
* JSON output shortcut
185+
*
186+
* @param array|mixed Callback data body, false will remove body key
187+
* @param int Callback status code
188+
* @param string Callback status text
189+
* @return string Response body data
190+
*/
191+
public function json($data, $statusCode=null, $statusText=null)
192+
{
193+
// Set Status Code
194+
if ($statusCode) {
195+
$this->setStatusCode($statusCode, $statusText);
196+
}
197+
198+
return $this->setFormat(Response::FORMAT_JSON)
199+
->setData($data)
200+
->send();
201+
}
182202
}

src/rest/Controller.php

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
* RESTful API Controller
1010
*
1111
* @author Nick Tsai <myintaer@gmail.com>
12-
* @version 1.1.4
12+
* @version 1.1.5
1313
* @link https://github.com/yidas/codeigniter-rest/
1414
* @see https://github.com/yidas/codeigniter-rest/blob/master/examples/RestController.php
1515
*
@@ -152,8 +152,6 @@ public function ajax($resourceID=NULL)
152152
*/
153153
protected function json($data=[], $bodyFormat=null, $statusCode=null, $statusText=null)
154154
{
155-
$this->response->setFormat(Response::FORMAT_JSON);
156-
157155
// Check default Body Format setting if not assigning
158156
$bodyFormat = ($bodyFormat!==null) ? $bodyFormat : $this->bodyFormat;
159157

@@ -165,14 +163,7 @@ protected function json($data=[], $bodyFormat=null, $statusCode=null, $statusTex
165163
$data = is_array($data) ? $data : [$data];
166164
}
167165

168-
// Set Status Code
169-
if ($statusCode) {
170-
$this->response->setStatusCode($statusCode);
171-
}
172-
173-
return $this->response
174-
->setData($data)
175-
->send();
166+
return $this->response->json($data, $statusCode);
176167
}
177168

178169
/**

0 commit comments

Comments
 (0)