Files
Woles-Framework/app/Core/Response.php

134 lines
2.6 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Core;
/**
* NovaCore Response Handler
* HTTP response wrapper
*/
class Response
{
private int $statusCode = 200;
private array $headers = [];
private $content = '';
/**
* Set status code
*/
public function status(int $code): self
{
$this->statusCode = $code;
return $this;
}
/**
* Set header
*/
public function header(string $name, string $value): self
{
$this->headers[$name] = $value;
return $this;
}
/**
* Set content type
*/
public function contentType(string $type): self
{
return $this->header('Content-Type', $type);
}
/**
* Set JSON response
*/
public function json(array $data, int $status = 200): self
{
$this->statusCode = $status;
$this->contentType('application/json');
$this->content = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
return $this;
}
/**
* Set HTML response
*/
public function html(string $content, int $status = 200): self
{
$this->statusCode = $status;
$this->contentType('text/html; charset=utf-8');
$this->content = $content;
return $this;
}
/**
* Set plain text response
*/
public function text(string $content, int $status = 200): self
{
$this->statusCode = $status;
$this->contentType('text/plain; charset=utf-8');
$this->content = $content;
return $this;
}
/**
* Redirect response
*/
public function redirect(string $url, int $status = 302): void
{
$this->statusCode = $status;
$this->header('Location', $url);
$this->send();
}
/**
* Set content
*/
public function content($content): self
{
$this->content = $content;
return $this;
}
/**
* Send response
*/
public function send(): void
{
// Set status code
http_response_code($this->statusCode);
// Set headers
foreach ($this->headers as $name => $value) {
header("{$name}: {$value}");
}
// Output content
echo $this->content;
}
/**
* Get status code
*/
public function getStatusCode(): int
{
return $this->statusCode;
}
/**
* Get headers
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* Get content
*/
public function getContent()
{
return $this->content;
}
}