Skip to content

Instantly share code, notes, and snippets.

@naosim
Created September 25, 2017 12:57
Show Gist options
  • Save naosim/70ea426a90e8092b62257e76a5fc9495 to your computer and use it in GitHub Desktop.
Save naosim/70ea426a90e8092b62257e76a5fc9495 to your computer and use it in GitHub Desktop.
ApiUtils
<?php
function api_forminput_jsonoutput($get_action, $post_action) {
header('Content-Type: application/json; charset=utf-8');
try {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo json_encode($post_action());
} else {
echo json_encode($get_action());
}
} catch(RuntimeException $e) {
if(get_class($e) === 'RequestValidationException') {
http_response_code(400);
echo json_encode(ResponseUtil::ng($e, 400));
} else {
http_response_code(500);
echo json_encode(ResponseUtil::ng($e, 500));
}
}
}
class ResponseUtil {
static function ok($ary) {
return array(
"status" => array(
"code" => 200
),
"result" => $ary
);
}
static function ng(RuntimeException $e, int $code = 500) {
return array(
"status" => array(
"code" => $code
),
"error" => array(
"type" => get_class($e),
"message" => $e->getMessage(),
"trace" => $e->getTrace(),
)
);
}
}
class RequestValidationException extends RuntimeException {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment