No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

71 líneas
1.6KB

  1. <?php
  2. declare(strict_types=1);
  3. namespace Core;
  4. class Response
  5. {
  6. protected string $content;
  7. protected int $status;
  8. protected array $headers;
  9. public function __construct(string $content = '', int $status = 200, array $headers = [])
  10. {
  11. $this->content = $content;
  12. $this->status = $status;
  13. $this->headers = $headers;
  14. }
  15. public static function json(array $data, int $status = 200): self
  16. {
  17. return new self(
  18. json_encode($data, JSON_PRETTY_PRINT),
  19. $status,
  20. ['Content-Type' => 'application/json']
  21. );
  22. }
  23. public static function redirect(string $url): self
  24. {
  25. return new self('', 302, ['Location' => $url]);
  26. }
  27. public static function notFound(string $message = 'Not found'): self
  28. {
  29. return new self($message, 404);
  30. }
  31. public static function serverError(string $message = 'Server error'): self
  32. {
  33. return new self($message, 500);
  34. }
  35. public function send(): void
  36. {
  37. // Flush session to disk before sending headers so it is persisted before
  38. // the browser follows any redirect (critical for OAuth state survival).
  39. if (session_status() === PHP_SESSION_ACTIVE) {
  40. session_write_close();
  41. }
  42. http_response_code($this->status);
  43. foreach ($this->headers as $name => $value) {
  44. header($name . ': ' . $value);
  45. }
  46. echo $this->content;
  47. }
  48. public function content(): string
  49. {
  50. return $this->content;
  51. }
  52. public function status(): int
  53. {
  54. return $this->status;
  55. }
  56. }

Powered by TurnKey Linux.