Skip to content

Instantly share code, notes, and snippets.

@skyler
Created September 27, 2012 18:04
Show Gist options
  • Save skyler/3795454 to your computer and use it in GitHub Desktop.
Save skyler/3795454 to your computer and use it in GitHub Desktop.
<?php
/**
* JSON server
*/
class JSONServer
{
/**
* @var the service object instance
*/
private $obj;
/**
* Create a new JSONServer instance
*
* @param $obj object the object to invoke service methods on
*/
public function __construct(RemoteService $obj)
{
$this->obj = $obj;
}
/**
* Handle a JSON POST request
*/
public function handle()
{
//print_r(get_class_methods($this->obj));
//die('i died');
$post = file_get_contents('php://input');
//error_log($post);
$response = array();
try {
if (empty($post)) {
throw new JSONFault(JSONFault::BAD_REQUEST, 'empty request.');
}
$request = json_decode($post, true);
if (empty($request['method'])) {
throw new JSONFault(JSONFault::BAD_REQUEST, 'method not specified.');
}
if (!method_exists($this->obj, $request['method'])) {
throw new JSONFault(JSONFault::METHOD_NOT_DEFINED,
"the specified method, {$request['method']}, is not defined.");
}
$ref = new ReflectionMethod(get_class($this->obj), $request['method']);
$params = array();
$arrp = $ref->getParameters();
// function parameters must be ordered
$missing = array();
foreach ($arrp as $param) {
$n = $param->getName();
if (isset($request['params'][$n])) {
$params[$n] = $request['params'][$n];
} else if ($param->isDefaultValueAvailable()) {
$params[$n] = $param->getDefaultValue();
} else {
$missing[] = $n;
}
}
if (!empty($missing)) {
$msg = "missing required parameter" . ((count($missing) > 1) ? 's: ' . implode($missing, ', ') : ": $missing[0]");
throw new JSONFault(JSONFault::MISSING_PARAM, $msg);
}
$this->obj->preProcessCallback();
$response = array(
'response' => $ref->invokeArgs($this->obj, $params),
'errors' => 0,
'errorMsg' => '',
);
} catch (JSONFault $f) {
error_log("JSONFault code {$f->getCode()} handling {$request['method']}: {$f->getMessage()}", E_USER_NOTICE);
$response = array(
'response' => null,
'errors' => $f->getCode(),
'errorMsg' => $f->getMessage(),
);
}
die(json_encode($response));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment