Files
scoutiq/app/Core/Response.php

90 lines
1.8 KiB
PHP

<?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");
}
}
}