Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

105 Zeilen
2.2KB

  1. <?php
  2. namespace Framework\Http;
  3. use InvalidArgumentException;
  4. class Response
  5. {
  6. const REDIRECT = 'REDIRECT';
  7. const HTML = 'HTML';
  8. const JSON = 'JSON';
  9. private string $type = 'HTML';
  10. private ?string $redirect = null;
  11. private mixed $content = '';
  12. private int $status = 200;
  13. private array $headers = [];
  14. public function content(mixed $content = null): mixed
  15. {
  16. if (is_null($content)) {
  17. return $this->content;
  18. }
  19. $this->content = $content;
  20. return $this;
  21. }
  22. public function status(int $status = null): int|static
  23. {
  24. if (is_null($status)) {
  25. return $this->status;
  26. }
  27. $this->status = $status;
  28. return $this;
  29. }
  30. public function header(string $key, string $value): static
  31. {
  32. $this->headers[$key] = $value;
  33. return $this;
  34. }
  35. public function redirect(string $redirect = null): mixed
  36. {
  37. if (is_null($redirect)) {
  38. return $this->redirect;
  39. }
  40. $this->redirect = $redirect;
  41. $this->type = static::REDIRECT;
  42. return $this;
  43. }
  44. public function json(mixed $content): static
  45. {
  46. $this->content = $content;
  47. $this->type = static::JSON;
  48. return $this;
  49. }
  50. public function type(string $type = null): string|static
  51. {
  52. if (is_null($type)) {
  53. return $this->type;
  54. }
  55. $this->type = $type;
  56. return $this;
  57. }
  58. public function send(): void
  59. {
  60. foreach ($this->headers as $key => $value) {
  61. header("{$key}: {$value}");
  62. }
  63. if ($this->type === static::HTML) {
  64. header('Content-Type: text/html');
  65. http_response_code($this->status);
  66. print $this->content;
  67. return;
  68. }
  69. if ($this->type === static::JSON) {
  70. header('Content-Type: application/json');
  71. http_response_code($this->status);
  72. print json_encode($this->content);
  73. return;
  74. }
  75. if ($this->type === static::REDIRECT) {
  76. header("Location: {$this->redirect}");
  77. return;
  78. }
  79. throw new InvalidArgumentException("{$this->type} is not a recognised type");
  80. }
  81. }

Powered by TurnKey Linux.