38 lines
1.1 KiB
PHP
38 lines
1.1 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/QdbHttpResponse.php';
|
|
|
|
function qdb_test_abort(array $body, int $status): never {
|
|
if (defined('QDB_TESTING') && QDB_TESTING) {
|
|
throw new QdbHttpResponse($body, $status);
|
|
}
|
|
http_response_code($status);
|
|
header('Content-Type: application/json; charset=UTF-8');
|
|
echo json_encode($body);
|
|
exit;
|
|
}
|
|
|
|
function json_success(mixed $data, int $status = 200): never {
|
|
qdb_test_abort(["ok" => true, "data" => $data], $status);
|
|
}
|
|
|
|
function json_error(string $code, string $message, int $status = 400): never {
|
|
qdb_test_abort(["ok" => false, "error" => ["code" => $code, "message" => $message]], $status);
|
|
}
|
|
|
|
function read_json_body(): array {
|
|
if (isset($GLOBALS['__TEST_JSON_BODY'])) {
|
|
$data = json_decode($GLOBALS['__TEST_JSON_BODY'], true);
|
|
if (!is_array($data)) {
|
|
json_error('INVALID_BODY', 'Request body must be valid JSON', 400);
|
|
}
|
|
return $data;
|
|
}
|
|
$raw = file_get_contents('php://input');
|
|
$data = json_decode($raw, true);
|
|
if (!is_array($data)) {
|
|
json_error('INVALID_BODY', 'Request body must be valid JSON', 400);
|
|
}
|
|
return $data;
|
|
}
|