Files
jared c90bdc8ac8
Lint / PHP (phpcs PSR-12) (push) Failing after 29s
Lint / JS (eslint) (push) Successful in 12s
style: auto-fix 1340 phpcs PSR-12 violations via phpcbf; exclude MissingNamespace and SideEffects
2026-04-13 20:56:10 -04:00

129 lines
3.2 KiB
PHP

<?php
/**
* ResponseHelper - Standardized JSON response formatting
*
* Provides consistent API response structure across all endpoints.
*/
class ResponseHelper
{
/**
* Send a success response
*
* @param array $data Additional data to include
* @param string $message Success message
* @param int $code HTTP status code
*/
public static function success($data = [], $message = 'Success', $code = 200)
{
http_response_code($code);
header('Content-Type: application/json');
echo json_encode(array_merge([
'success' => true,
'message' => $message
], $data));
exit;
}
/**
* Send an error response
*
* @param string $message Error message
* @param int $code HTTP status code
* @param array $data Additional data to include
*/
public static function error($message, $code = 400, $data = [])
{
http_response_code($code);
header('Content-Type: application/json');
echo json_encode(array_merge([
'success' => false,
'error' => $message
], $data));
exit;
}
/**
* Send an unauthorized response (401)
*
* @param string $message Error message
*/
public static function unauthorized($message = 'Authentication required')
{
self::error($message, 401);
}
/**
* Send a forbidden response (403)
*
* @param string $message Error message
*/
public static function forbidden($message = 'Access denied')
{
self::error($message, 403);
}
/**
* Send a not found response (404)
*
* @param string $message Error message
*/
public static function notFound($message = 'Resource not found')
{
self::error($message, 404);
}
/**
* Send a validation error response (422)
*
* @param array $errors Validation errors
* @param string $message Error message
*/
public static function validationError($errors, $message = 'Validation failed')
{
self::error($message, 422, ['validation_errors' => $errors]);
}
/**
* Send a server error response (500)
*
* @param string $message Error message
*/
public static function serverError($message = 'Internal server error')
{
self::error($message, 500);
}
/**
* Send a rate limit exceeded response (429)
*
* @param int $retryAfter Seconds until retry is allowed
* @param string $message Error message
*/
public static function rateLimitExceeded($retryAfter = 60, $message = 'Rate limit exceeded')
{
header('Retry-After: ' . $retryAfter);
self::error($message, 429, ['retry_after' => $retryAfter]);
}
/**
* Send a created response (201)
*
* @param array $data Resource data
* @param string $message Success message
*/
public static function created($data = [], $message = 'Resource created')
{
self::success($data, $message, 201);
}
/**
* Send a no content response (204)
*/
public static function noContent()
{
http_response_code(204);
exit;
}
}