response.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. class response {
  3. private int $code;
  4. private array $parsed;
  5. private array $headers;
  6. private string $version;
  7. private string $content;
  8. public function __construct(string $content) {
  9. $parts = explode("\r\n\r\n", $content);
  10. $head = array_shift($parts);
  11. $body = join("\r\n\r\n", $parts);
  12. $this->parse_head($head);
  13. $this->parse_body($body);
  14. }
  15. public function get_code(): int {
  16. return $this->code;
  17. }
  18. public function get_version(): string {
  19. return $this->version;
  20. }
  21. public function get_header(
  22. string $name,
  23. ?string $fallback = null
  24. ): ?string {
  25. if (array_key_exists($name, $this->headers)) {
  26. return $this->headers[$name];
  27. }
  28. return $fallback;
  29. }
  30. public function get_content(): string {
  31. return $this->content;
  32. }
  33. public function get_json_content(): array {
  34. return $this->parsed;
  35. }
  36. private function parse_body(string $body): void {
  37. $type = $this->get_header('Content-Type', 'text/plain'));
  38. $is_json = strpos($type, 'json') !== -1;
  39. $this->content = $body;
  40. $this->parsed = array();
  41. if ($is_json) {
  42. $this->parsed = json_decode($body);
  43. }
  44. }
  45. private function parse_head(string $head): void {
  46. $lines = explode("\r\n", $head);
  47. $first = array_shift($lines);
  48. $this->parse_first_line($first);
  49. $this->parse_headers($lines);
  50. }
  51. private function parse_first_line(string $line): void {
  52. $parts = explode(' ', $line);
  53. $this->version = array_shift($parts);
  54. $this->code = int(array_shift($parts));
  55. }
  56. private function parse_headers(array $lines): void {
  57. $this->headers = array();
  58. foreach ($lines as $line) {
  59. $parts = explode(':', $line);
  60. $name = array_shift($parts);
  61. $content = ltrim(join(':', $parts));
  62. $this->headers[$name] = $content;
  63. }
  64. }
  65. }