Response Macro for JSend

Submitted by icylace - 9 years ago

I made a response macro that makes use of the JSend specification (http://labs.omniti.com/labs/jsend). UPDATE (2014-09-15): Added the setting of the content type.

//
// Defines a server response that follows the JSend specification
// (http://labs.omniti.com/labs/jsend).
//
Response::macro('jsend', function ($status, $data = null, $message = null, $code = null) {
  switch ($status) {
    case 'success':
    case 'fail':
      $content = ['status' => $status, 'data' => $data];
      break;
    default:
      $content = ['status' => 'error', 'message' => $message];
      if ($data) {
        $content['data'] = $data;
      }
      if ($code) {
        $content['code'] = $code;
      }
  }
  $response = Response::make($content);
  $response->header('Content-Type', 'application/json');
  return $response;
});