Response.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. declare(strict_types=1);
  3. namespace Glacier\Core;
  4. /**
  5. * 统一响应出口:HTML / JSON / 文本 / 重定向。
  6. * 输出后立即终止(never)。
  7. */
  8. final class Response
  9. {
  10. public static function html(string $body, int $status = 200, array $headers = []): never
  11. {
  12. http_response_code($status);
  13. header('Content-Type: text/html; charset=utf-8');
  14. foreach ($headers as $name => $value) {
  15. header($name . ': ' . $value);
  16. }
  17. echo $body;
  18. exit;
  19. }
  20. public static function json(mixed $data, int $status = 200): never
  21. {
  22. http_response_code($status);
  23. header('Content-Type: application/json; charset=utf-8');
  24. echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  25. exit;
  26. }
  27. public static function text(string $body, int $status = 200): never
  28. {
  29. http_response_code($status);
  30. header('Content-Type: text/plain; charset=utf-8');
  31. echo $body;
  32. exit;
  33. }
  34. public static function redirect(string $location, int $status = 302): never
  35. {
  36. http_response_code($status);
  37. header('Location: ' . $location);
  38. exit;
  39. }
  40. }