dx4 v2
This commit is contained in:
+31
-6
@@ -1,38 +1,54 @@
|
||||
<?php
|
||||
|
||||
/** @param callable(_K_Api): void $apiFun */
|
||||
function CreateApi(callable $apiFun)
|
||||
function CreateApi(callable $apiFun, bool $devmode = false)
|
||||
{
|
||||
header("Access-Control-Allow-Origin: *");
|
||||
header("Access-Control-Allow-Headers: Content-Type");
|
||||
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
|
||||
header("Access-Control-Allow-Headers: Content-Type, Authorization");
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
|
||||
http_response_code(200);
|
||||
exit;
|
||||
}
|
||||
|
||||
$api = new _K_Api();
|
||||
$api->dev_mode = $devmode;
|
||||
$apiFun($api);
|
||||
$api->end();
|
||||
}
|
||||
class _K_Api
|
||||
{
|
||||
private $has_exec = false;
|
||||
public $dev_mode = false;
|
||||
/** @param callable(_K_ApiRequest): string|array|int|float|bool $fun */
|
||||
public function on(string $route, string $method, callable $fun)
|
||||
{
|
||||
$request_url = (count($_GET) > 0 ? array_keys($_GET)[0] : '');
|
||||
$r = str_starts_with($route, '/') ? substr($route, 1) : $route;
|
||||
if ($this->has_exec) return;
|
||||
if ($r != $request_url) {
|
||||
return;
|
||||
} else {
|
||||
$this->has_exec = true;
|
||||
if ($_SERVER['REQUEST_METHOD'] != $method) {
|
||||
|
||||
$req_method = $_SERVER['REQUEST_METHOD'];
|
||||
if ($req_method != $method) {
|
||||
http_response_code(405);
|
||||
die("ERROR: unsupported method ($method available)");
|
||||
$_a = "";
|
||||
if ($this->dev_mode)
|
||||
$_a = " - using $req_method, available $method";
|
||||
die("ERROR: Method Not Allowed" . $_a);
|
||||
return;
|
||||
}
|
||||
|
||||
$data = [];
|
||||
if ($method == 'GET' && count($_GET) > 1) {
|
||||
$data = array_slice(array_keys($_GET), 1);
|
||||
} else if ($method == 'POST' && count($_POST) > 0) {
|
||||
$data = $_POST;
|
||||
}
|
||||
|
||||
$fun = $fun(new _K_ApiRequest($data));
|
||||
if (is_string($fun) || is_numeric($fun)) {
|
||||
if (json_validate($fun) && !is_numeric($fun)) {
|
||||
@@ -43,8 +59,17 @@ class _K_Api
|
||||
Header('Content-Type: application/json');
|
||||
echo json_encode($fun);
|
||||
} else {
|
||||
die("ERROR: unknown return type");
|
||||
http_response_code(500);
|
||||
$_a = "Internal Server Error";
|
||||
if ($this->dev_mode) {
|
||||
$_type = gettype($fun);
|
||||
$_a = "unknown return type ($_type), (available bool, array, numeric, string)";
|
||||
}
|
||||
die("ERROR: " . $_a);
|
||||
return;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +77,7 @@ class _K_Api
|
||||
{
|
||||
if (!$this->has_exec) {
|
||||
http_response_code(404);
|
||||
echo '404';
|
||||
echo 'ERROR: Not Found';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user