119 lines
3.1 KiB
PHP
119 lines
3.1 KiB
PHP
<?php
|
|
|
|
const VERIFY_STRING = "string";
|
|
const VERIFY_INT = "integer";
|
|
const VERIFY_NUMBER = "number";
|
|
|
|
const DEBUG = true;
|
|
|
|
|
|
abstract class Api {
|
|
|
|
protected $success = true; // bool
|
|
protected $message; // string
|
|
protected $result; // any
|
|
|
|
protected $methods; // array
|
|
protected $data; // array
|
|
|
|
|
|
function __construct(){
|
|
header("Content-Type: application/json");
|
|
|
|
try {
|
|
$this->parseRequest();
|
|
} catch (ApiException $e) {
|
|
$this->success = false;
|
|
$this->message = $e;
|
|
}
|
|
|
|
if(empty($this->data)){
|
|
$this->success = false;
|
|
$this->message = "No data"; // Todo: Specify missing fields in output
|
|
}
|
|
|
|
if($this->success){
|
|
try {
|
|
$this->execute();
|
|
}
|
|
catch (Exception | DatabaseException $e){
|
|
$this->success = false;
|
|
$this->message = $e;
|
|
}
|
|
}
|
|
|
|
$this->printResult();
|
|
}
|
|
|
|
private function printResult(){
|
|
$returns['status'] = $this->success;
|
|
$returns['message'] = $this->message;
|
|
$returns['data'] = $this->result ?? $this->message;
|
|
|
|
if(DEBUG){
|
|
$returns['debug'][] = debug_backtrace();
|
|
$returns['debug']["methods"] = $this->methods;
|
|
}
|
|
|
|
echo json_encode( $returns );
|
|
}
|
|
|
|
/**
|
|
* @throws DatabaseException
|
|
*/
|
|
protected function execute(){ }
|
|
|
|
/**
|
|
* @throws ApiException
|
|
*/
|
|
private function parseRequest(){
|
|
foreach ($this->methods as $method => $args){
|
|
if($method === "POST"){
|
|
$requestData = $_POST;
|
|
}
|
|
elseif($method === "GET"){
|
|
$requestData = $_GET;
|
|
}
|
|
elseif($method === "URI"){
|
|
$requestData = [];
|
|
foreach ($args as $k => $arg) {
|
|
$requestData[$arg['keyword']] = $_GET['args'][$k];
|
|
}
|
|
}
|
|
else {
|
|
throw new ApiException("Unrecognized method in function.");
|
|
}
|
|
|
|
foreach ($args as $arg){
|
|
if(isset($requestData[ $arg['keyword'] ])){
|
|
$value = $requestData[ $arg['keyword'] ];
|
|
|
|
switch ($arg['type']){
|
|
case VERIFY_STRING:
|
|
$value = (string) $value;
|
|
break;
|
|
case VERIFY_INT:
|
|
$value = (int) $value;
|
|
break;
|
|
case VERIFY_NUMBER:
|
|
$value = (double) $value;
|
|
break;
|
|
default:
|
|
throw new ApiException("Unknown argument type");
|
|
}
|
|
|
|
$this->data[$arg['keyword']] = $value;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
class ApiException extends Exception {
|
|
function __construct($message = "", $code = 0, Throwable $previous = null){
|
|
parent::__construct($message, $code, $previous);
|
|
}
|
|
} |