end(); } class _K_Api { private $has_exec = 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 ($r != $request_url) { return; } else { $this->has_exec = true; if ($_SERVER['REQUEST_METHOD'] != $method) { http_response_code(405); die("ERROR: unsupported method ($method available)"); 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)) { Header('Content-Type: application/json'); } echo $fun; } else if (is_array($fun) || is_bool($fun)) { Header('Content-Type: application/json'); echo json_encode($fun); } else { die("ERROR: unknown return type"); } } } public function end() { if (!$this->has_exec) { http_response_code(404); echo '404'; } } } class _K_ApiRequest { public array $data; public _K_ApiResponse $res; public function __construct(array $data) { $this->data = $data; $this->res = new _K_ApiResponse($this); } public function hasData(array $dataArr) { foreach ($dataArr as $i) { if (!isset($this->data[$i])) { return false; } } return true; } } class _K_ApiResponse { public function __construct($req) {} public function code(int $httpCode) { http_response_code($httpCode); } }