RestClient::parse_response PHP Method

parse_response() public method

public parse_response ( $response )
    public function parse_response($response)
    {
        $headers = [];
        $this->response_status_lines = [];
        $line = strtok($response, "\n");
        do {
            if (strlen(trim($line)) == 0) {
                // Since we tokenize on \n, use the remaining \r to detect empty lines.
                if (count($headers) > 0) {
                    break;
                }
                // Must be the newline after headers, move on to response body
            } elseif (strpos($line, 'HTTP') === 0) {
                // One or more HTTP status lines
                $this->response_status_lines[] = trim($line);
            } else {
                // Has to be a header
                list($key, $value) = explode(':', $line, 2);
                $key = trim(strtolower(str_replace('-', '_', $key)));
                $value = trim($value);
                if (empty($headers[$key])) {
                    $headers[$key] = $value;
                } elseif (is_array($headers[$key])) {
                    $headers[$key][] = $value;
                } else {
                    $headers[$key] = [$headers[$key], $value];
                }
            }
        } while ($line = strtok("\n"));
        $this->headers = (object) $headers;
        $this->response = strtok("");
    }

Usage Example

Example #1
0
 public function test_status_only_response()
 {
     $RESPONSE = "HTTP/1.1 100 Continue\r\n\r\n";
     $api = new RestClient();
     // bypass request execution to inject controlled response data.
     $api->parse_response($RESPONSE);
     $this->assertEquals(["HTTP/1.1 100 Continue"], $api->response_status_lines);
     $this->assertEquals((object) [], $api->headers);
     $this->assertEquals("", $api->response);
 }