View file app\Core\Response.php

File size: 1.39Kb
<?php

namespace App\Core;

class Response
{
    private string $content;
    private int $status;
    private array $headers = [];

    public function __construct(string $content = '', int $status = 200)
    {
        $this->content = $content;
        $this->status = $status;
    }

    public static function json(array $data, int $status = 200): self
    {
        $response = new self(json_encode($data), $status);
        $response->setHeader('Content-Type', 'application/json');
        return $response;
    }

    public static function redirect(string $url): self
    {
        $response = new self('', 302);
        $response->setHeader('Location', $url);
        return $response;
    }

    public function setHeader(string $name, string $value): self
    {
        $this->headers[$name] = $value;
        return $this;
    }

    public function send(): void
    {
        http_response_code($this->status);

        // Prevent browser caching for dynamic content
        if (!isset($this->headers['Cache-Control'])) {
            header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
            header("Pragma: no-cache");
            header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
        }

        foreach ($this->headers as $name => $value) {
            header("$name: $value");
        }
        echo $this->content;
    }
}