| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- class response {
- private int $code;
- private array $parsed;
- private array $headers;
- private string $version;
- private string $content;
- public function __construct(string $content) {
- $parts = explode("\r\n\r\n", $content);
- $head = array_shift($parts);
- $body = join("\r\n\r\n", $parts);
- $this->parse_head($head);
- $this->parse_body($body);
- }
- public function get_code(): int {
- return $this->code;
- }
- public function get_version(): string {
- return $this->version;
- }
- public function get_header(
- string $name,
- ?string $fallback = null
- ): ?string {
- if (array_key_exists($name, $this->headers)) {
- return $this->headers[$name];
- }
- return $fallback;
- }
- public function get_content(): string {
- return $this->content;
- }
- public function get_json_content(): array {
- return $this->parsed;
- }
- private function parse_body(string $body): void {
- $type = $this->get_header('Content-Type', 'text/plain'));
- $is_json = strpos($type, 'json') !== -1;
- $this->content = $body;
- $this->parsed = array();
- if ($is_json) {
- $this->parsed = json_decode($body);
- }
- }
- private function parse_head(string $head): void {
- $lines = explode("\r\n", $head);
- $first = array_shift($lines);
-
- $this->parse_first_line($first);
- $this->parse_headers($lines);
- }
- private function parse_first_line(string $line): void {
- $parts = explode(' ', $line);
- $this->version = array_shift($parts);
- $this->code = int(array_shift($parts));
- }
- private function parse_headers(array $lines): void {
- $this->headers = array();
- foreach ($lines as $line) {
- $parts = explode(':', $line);
- $name = array_shift($parts);
- $content = ltrim(join(':', $parts));
- $this->headers[$name] = $content;
- }
- }
- }
|