Complete Phase 1: MVC, DB migrations, Auth, RBAC, Security, and Views
This commit is contained in:
89
app/Core/Response.php
Normal file
89
app/Core/Response.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
class Response
|
||||
{
|
||||
private int $statusCode = 200;
|
||||
private array $headers = [];
|
||||
|
||||
/**
|
||||
* Set the HTTP status code.
|
||||
*/
|
||||
public function setStatusCode(int $code): self
|
||||
{
|
||||
$this->statusCode = $code;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HTTP status code.
|
||||
*/
|
||||
public function getStatusCode(): int
|
||||
{
|
||||
return $this->statusCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a header.
|
||||
*/
|
||||
public function header(string $name, string $value): self
|
||||
{
|
||||
$this->headers[$name] = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set redirect path.
|
||||
*/
|
||||
public function redirect(string $url): void
|
||||
{
|
||||
header("Location: " . $url);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Output JSON data.
|
||||
*/
|
||||
public function json(mixed $data, int $code = 200): void
|
||||
{
|
||||
$this->setStatusCode($code);
|
||||
$this->header('Content-Type', 'application/json; charset=utf-8');
|
||||
|
||||
$this->sendHeaders();
|
||||
http_response_code($this->statusCode);
|
||||
|
||||
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Output raw HTML or string content.
|
||||
*/
|
||||
public function html(string $content, int $code = 200): void
|
||||
{
|
||||
$this->setStatusCode($code);
|
||||
if (!isset($this->headers['Content-Type'])) {
|
||||
$this->header('Content-Type', 'text/html; charset=utf-8');
|
||||
}
|
||||
|
||||
$this->sendHeaders();
|
||||
http_response_code($this->statusCode);
|
||||
|
||||
echo $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send all buffered headers.
|
||||
*/
|
||||
public function sendHeaders(): void
|
||||
{
|
||||
if (headers_sent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($this->headers as $name => $value) {
|
||||
header("$name: $value");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user