Files
musadaq-saas/app/bootstrap/response.php
2026-05-03 18:19:24 +03:00

59 lines
1.7 KiB
PHP

<?php
/**
* Standardized JSON Responses with Multi-Level Logging
*/
declare(strict_types=1);
function json_response(bool $success, $data = null, ?string $message = null, int $code = 200) {
// 1. Prepare Log Entry
$logEntry = sprintf(
"API %s %s | Code: %d | Success: %s | Message: %s | Data: %s",
$_SERVER['REQUEST_METHOD'] ?? 'CLI',
$_SERVER['REQUEST_URI'] ?? '',
$code,
$success ? 'YES' : 'NO',
$message ?? 'N/A',
json_encode($data, JSON_UNESCAPED_UNICODE)
);
// 2. Log to Standard PHP Error Log (Visible in CloudPanel Logs)
error_log($logEntry);
// 3. Try to log to custom app.log in storage folder
$logDir = STORAGE_PATH . '/logs';
$logFile = $logDir . '/app.log';
try {
if (!is_dir($logDir)) {
@mkdir($logDir, 0775, true);
}
if (is_writable($logDir) || is_writable($logFile)) {
@file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] " . $logEntry . "\n", FILE_APPEND);
}
} catch (\Exception $e) {
// Fallback if filesystem is locked
}
// 4. HTTP Response
header('Content-Type: application/json; charset=utf-8');
http_response_code($code);
echo json_encode([
'success' => $success,
'data' => $data,
'message' => $message,
'timestamp' => date('c')
], JSON_UNESCAPED_UNICODE);
exit;
}
function json_error(string $message, int $code = 400, $errors = null) {
json_response(false, $errors, $message, $code);
}
function json_success($data = null, ?string $message = 'Success', int $code = 200) {
json_response(true, $data, $message, $code);
}