68 lines
2.0 KiB
PHP
68 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Core;
|
|
|
|
class Response
|
|
{
|
|
public static function json(array $data, int $statusCode = 200, array $headers = []): void
|
|
{
|
|
http_response_code($statusCode);
|
|
|
|
$defaultHeaders = [
|
|
'Content-Type' => 'application/json; charset=utf-8',
|
|
'X-Content-Type-Options' => 'nosniff',
|
|
'X-Frame-Options' => 'DENY',
|
|
'X-XSS-Protection' => '1; mode=block',
|
|
'Access-Control-Allow-Origin' => '*',
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
|
|
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-User-Id, X-Device-Fingerprint, X-Timestamp, X-Nonce, X-Signature',
|
|
];
|
|
|
|
foreach (array_merge($defaultHeaders, $headers) as $name => $val) {
|
|
header("$name: $val");
|
|
}
|
|
|
|
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
exit;
|
|
}
|
|
|
|
public static function success(mixed $data = null, string $message = 'Success', int $statusCode = 200): void
|
|
{
|
|
self::json([
|
|
'success' => true,
|
|
'status' => 'success',
|
|
'message' => $message,
|
|
'data' => $data,
|
|
'timestamp' => time(),
|
|
], $statusCode);
|
|
}
|
|
|
|
public static function error(string $message = 'An error occurred', int $statusCode = 400, array $errors = []): void
|
|
{
|
|
self::json([
|
|
'success' => false,
|
|
'status' => 'error',
|
|
'message' => $message,
|
|
'errors' => $errors,
|
|
'timestamp' => time(),
|
|
], $statusCode);
|
|
}
|
|
|
|
public static function unauthorized(string $message = 'Unauthorized access'): void
|
|
{
|
|
self::error($message, 401);
|
|
}
|
|
|
|
public static function forbidden(string $message = 'Forbidden'): void
|
|
{
|
|
self::error($message, 403);
|
|
}
|
|
|
|
public static function notFound(string $message = 'Resource not found'): void
|
|
{
|
|
self::error($message, 404);
|
|
}
|
|
}
|