Files
controls-web/lasuca/api/helpers/response.php
2026-02-17 09:29:34 -06:00

85 lines
1.7 KiB
PHP

<?php
// phpcs:ignoreFile
/**
* API Response Helpers
*/
declare(strict_types=1);
/**
* Send a JSON success response.
*/
function api_success(array $data = [], int $statusCode = 200): void
{
http_response_code($statusCode);
echo json_encode([
'success' => true,
'data' => $data,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit();
}
/**
* Send a JSON error response.
*/
function api_error(string $message, int $statusCode = 400, array $details = []): void
{
http_response_code($statusCode);
$response = [
'success' => false,
'error' => [
'message' => $message,
'code' => $statusCode,
],
];
if (!empty($details)) {
$response['error']['details'] = $details;
}
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit();
}
/**
* Get JSON body from request.
*/
function api_get_json_body(): array
{
$rawBody = file_get_contents('php://input');
if ($rawBody === '' || $rawBody === false) {
return [];
}
$decoded = json_decode($rawBody, true);
if (!is_array($decoded)) {
return [];
}
return $decoded;
}
/**
* Require specific fields in request body.
*/
function api_require_fields(array $body, array $fields): void
{
$missing = [];
foreach ($fields as $field) {
if (!isset($body[$field]) || (is_string($body[$field]) && trim($body[$field]) === '')) {
$missing[] = $field;
}
}
if (!empty($missing)) {
api_error('Missing required fields: ' . implode(', ', $missing), 422);
}
}