parse_head($head); $this->parse_body($body); } /** * That return status code of the response. * * @return int Number status of the response. */ public function get_code(): int { return $this->code; } /** * That return HTTP protocol version of the response, like "HTTP/2" * for example. * * @return string HTTP protocol version, like "HTTP/2". */ public function get_version(): string { return $this->version; } /** * That function return selected header of the response. When header did * not being received, then it return content given to fallback parameter. * * @param string $name Name of the header. * @param ?string $fallback Value to return when header not exists. * @return ?string Content of the header or fallback. */ public function get_header( string $name, ?string $fallback = null ): ?string { $name = strtolower($name); if (array_key_exists($name, $this->headers)) { return $this->headers[$name]; } return $fallback; } /** * That function return RAW content of the response body. * * @return string RAW content of the body. */ public function receive_raw(): string { return $this->content; } /** * That return parsed content of the body, when content type of the * response had been json. When content had been received in other form, * then empty array had been returned. * * @return array Parsed content of the body of empty array. */ public function receive_array(): array { return $this->parsed; } /** * That function parse body section of the response. * * @param string $body Body part of the response. */ private function parse_body(string $body): void { $type = $this->get_header('Content-Type', 'text/plain'); $is_json = strpos($type, 'json') !== false; $this->content = $body; $result = array(); if ($is_json) { $result = json_decode($body, true); } /* Because json_decode could fail, when response had bad syntax. */ if (gettype($result) !== 'array') { $result = array(); } $this->parsed = $result; } /** * That function is responsible for parsing head of the response. * * @param string $head RAW head content of the response. */ 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); } /** * That function parse first line, with status and HTTP version, of * the response. * * @param string $line First line of the response. */ private function parse_first_line(string $line): void { $parts = explode(' ', $line); $this->version = array_shift($parts); $this->code = intval(array_shift($parts)); } /** * That parse headers section of the response. * * @param array $lines Lines from headers section. */ private function parse_headers(array $lines): void { $this->headers = array(); foreach ($lines as $line) { $parts = explode(':', $line); if (count($parts) < 2) { continue; } $name = array_shift($parts); $name= strtolower($name); $content = ltrim(join(':', $parts)); $this->headers[$name] = $content; } } }