Initial commit
This commit is contained in:
93
backend/app/Core/Response.php
Normal file
93
backend/app/Core/Response.php
Normal file
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* Handles generating and sending consistent API and HTML responses.
|
||||
*/
|
||||
class Response
|
||||
{
|
||||
private int $statusCode = 200;
|
||||
private array $headers = [];
|
||||
|
||||
public function setStatusCode(int $code): self
|
||||
{
|
||||
$this->statusCode = $code;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStatusCode(): int
|
||||
{
|
||||
return $this->statusCode;
|
||||
}
|
||||
|
||||
public function setHeader(string $name, string $value): self
|
||||
{
|
||||
$this->headers[$name] = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send JSON response and terminate execution
|
||||
*
|
||||
* @param mixed $data
|
||||
* @param int $code
|
||||
* @return void
|
||||
*/
|
||||
public function json($data, int $code = 200): void
|
||||
{
|
||||
$this->setStatusCode($code);
|
||||
$this->setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
|
||||
// Setup base CORS headers for our API
|
||||
$this->setHeader('Access-Control-Allow-Origin', '*');
|
||||
$this->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
|
||||
$this->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
|
||||
|
||||
$this->sendHeaders();
|
||||
http_response_code($this->statusCode);
|
||||
|
||||
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send success JSON response
|
||||
*/
|
||||
public function success(string $message, array $data = [], int $code = 200): void
|
||||
{
|
||||
$this->json([
|
||||
'status' => 'success',
|
||||
'message' => $message,
|
||||
'data' => $data
|
||||
], $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send error JSON response
|
||||
*/
|
||||
public function error(string $message, int $code = 400, array $errors = []): void
|
||||
{
|
||||
$response = [
|
||||
'status' => 'error',
|
||||
'message' => $message
|
||||
];
|
||||
|
||||
if (!empty($errors)) {
|
||||
$response['errors'] = $errors;
|
||||
}
|
||||
|
||||
$this->json($response, $code);
|
||||
}
|
||||
|
||||
private function sendHeaders(): void
|
||||
{
|
||||
if (headers_sent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($this->headers as $name => $value) {
|
||||
header("{$name}: {$value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user