Skip to content

Instantly share code, notes, and snippets.

@imcarvalho
Created December 3, 2015 11:13
Show Gist options
  • Save imcarvalho/2d16567ef331d2b72059 to your computer and use it in GitHub Desktop.
Save imcarvalho/2d16567ef331d2b72059 to your computer and use it in GitHub Desktop.
<?php
class JsonResponse implements ResponseInterface
{
/**
* Return a success response.
* Set the header:
* Content-Type: application/json
*
* @param array $body the body of the response
*/
static public function success(array $body)
{
header('Content-Type: application/json');
http_response_code(self::STATUS_SUCCESS);
exit(json_encode($body));
}
/**
* Return a error response.
* Set the header:
* Content-Type: application/json
*
* @param string $message the message for the client
* @param array $body the body of the response
*/
static public function badRequest($message, array $body = null)
{
header('Content-Type: application/json');
http_response_code(self::STATUS_BAD_REQUEST);
$response = $body;
$response['msg'] = $message;
exit(json_encode($response));
}
/**
* Return a error response.
* Set the header
* Content-Type: application/json
*
* @param string $message the message for the client
* @param array $body the body of the response
*/
static public function forbidden($message, array $body = null)
{
header('Content-Type: application/json');
http_response_code(self::STATUS_FORBIDDEN);
$response = $body;
$response['msg'] = $message;
exit(json_encode($response));
}
/**
* Return a error response.
* Set the headers
* Content-Type: application/json
*
* @param string $message the message for the client
* @param array $body the body of the response
*/
static public function serverError($message, array $body = null)
{
header('Content-Type: application/json');
http_response_code(self::STATUS_SERVER_ERROR);
$response = $body;
$response['msg'] = $message;
exit(json_encode($response));
}
/**
* Return a error response.
* Set the headers
* Content-Type: application/json
*
* @param string $message the message for the client
* @param array $body the body of the response
*/
static public function notFound($message, array $body = null)
{
header('Content-Type: application/json');
http_response_code(self::STATUS_NOT_FOUND);
$response = $body;
$response['msg'] = $message;
exit(json_encode($response));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment