Files
2026-06-12 21:26:30 +07:00

63 lines
1.8 KiB
PHP

<?php
// ============================================================
// config/helpers.php — Shared utility functions
// ============================================================
/**
* Global exception handler to return JSON on fatal errors.
*/
set_exception_handler(function(Throwable $e) {
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
http_response_code(500);
echo json_encode([
'error' => 'Internal Server Error',
'message' => $e->getMessage(),
'file' => basename($e->getFile()),
'line' => $e->getLine()
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
});
/**
* Set JSON response headers and output data.
*/
function jsonResponse(mixed $data, int $status = 200): void {
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
http_response_code($status);
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
/**
* Return decoded JSON body from the request.
*/
function getRequestBody(): array {
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
return is_array($data) ? $data : [];
}
/**
* Get the HTTP request method.
*/
function getMethod(): string {
return strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
}
/**
* Handle CORS preflight.
*/
function handlePreflight(): void {
if (getMethod() === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
http_response_code(204);
exit;
}
}