62 lines
1.3 KiB
PHP
62 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core\Http;
|
|
|
|
class Response
|
|
{
|
|
private int $statusCode = 200;
|
|
private array $headers = [];
|
|
private string $content = '';
|
|
|
|
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;
|
|
}
|
|
|
|
public function setContent(string $content): self
|
|
{
|
|
$this->content = $content;
|
|
return $this;
|
|
}
|
|
|
|
public function json(mixed $data, int $statusCode = 200): self
|
|
{
|
|
$this->statusCode = $statusCode;
|
|
$this->setHeader('Content-Type', 'application/json');
|
|
$this->content = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
|
return $this;
|
|
}
|
|
|
|
public function redirect(string $url, int $statusCode = 302): self
|
|
{
|
|
$this->statusCode = $statusCode;
|
|
$this->setHeader('Location', $url);
|
|
return $this;
|
|
}
|
|
|
|
public function send(): void
|
|
{
|
|
http_response_code($this->statusCode);
|
|
|
|
foreach ($this->headers as $name => $value) {
|
|
header("{$name}: {$value}");
|
|
}
|
|
|
|
echo $this->content;
|
|
}
|
|
}
|