Skip to content

Instantly share code, notes, and snippets.

@lukesUbuntu
Created January 3, 2018 10:42
Show Gist options
  • Save lukesUbuntu/a031a29846cae7aebecd92b8ac52acf5 to your computer and use it in GitHub Desktop.
Save lukesUbuntu/a031a29846cae7aebecd92b8ac52acf5 to your computer and use it in GitHub Desktop.
Handy json output class
<?php
/**
* User: luke hardiman
* Date: 2/20/15
* Time: 11:23 PM
* @Description : Handy json output class
*/
namespace Api;
class Response
{
/**
* @param $data response to send back as JSON with Callback
* @param bool|true $success
* @param cross dom allowed or disabled for this request
* @param int $status_code of response default 200
* @param string $status_message of response default OK
* @todo move cross_dom default to false but need to test all transactions before this
*/
public function send($data, $success = true, $cross_dom = true, $status_code = 200, $status_message = "OK")
{
//new response
if ($success == false){
$status_code = 202;
$status_message = "Invalid Request";
}
//http_response_code($status_code);
header("HTTP/1.1 {$status_code} {$status_message}");
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
//encode call
$json = json_encode(array('success' => $success, 'data' => $data));
echo (isset($_GET['callback'])
? "{$_GET['callback']}($json)"
: $json);
//exit; //kill from other processing
exit;//die end the request
}
public function action(){
return (isset($_GET['action']) && !empty($_GET['action'])) ? strtolower($_GET['action']) : false;
}
public function getRequiredRequest($attr,$type = 'GET'){
if (strtoupper($type == 'POST')){
if (!isset($_POST[$attr]) || empty($_POST[$attr]))
return $this->send("missing $attr",false);
return $_POST[$attr];
}
if (strtoupper($type == 'GET')){
if (!isset($_GET[$attr]) || empty($_GET[$attr]))
return $this->send("missing $attr",false);
return $_GET[$attr];
}
}
public function getRequest($attr,$type = 'GET'){
if (strtoupper($type == 'POST')){
if (!isset($_POST[$attr]) || empty($_POST[$attr]))
return false;
return $_POST[$attr];
}
if (strtoupper($type == 'GET')){
if (!isset($_GET[$attr]) || empty($_GET[$attr]))
return false;
return $_GET[$attr];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment