Example #1
0
 /**
  * Parses a raw response string, including headers and body, and returns a Response object.
  *
  * @param string $response
  *
  * @return \Brick\Http\Response
  *
  * @throws \RuntimeException
  */
 public static function parse($response)
 {
     $responseObject = new Response();
     if (preg_match('/^HTTP\\/([0-9]\\.[0-9]) ([0-9]{3}) .*\\r\\n/', $response, $matches) == 0) {
         throw new \RuntimeException('Could not parse response (error 1).');
     }
     list($line, $protocolVersion, $statusCode) = $matches;
     $responseObject->setProtocolVersion($protocolVersion);
     $responseObject->setStatusCode($statusCode);
     $response = substr($response, strlen($line));
     for (;;) {
         $pos = strpos($response, Message::CRLF);
         if ($pos === false) {
             throw new \RuntimeException('Could not parse response (error 2).');
         }
         if ($pos == 0) {
             break;
         }
         $header = substr($response, 0, $pos);
         if (preg_match('/^(\\S+):\\s*(.*)$/', $header, $matches) == 0) {
             throw new \RuntimeException('Could not parse response (error 3).');
         }
         list($line, $name, $value) = $matches;
         if (strtolower($name) == 'set-cookie') {
             $responseObject->setCookie(Cookie::parse($value));
         } else {
             $responseObject->addHeader($name, $value);
         }
         $response = substr($response, strlen($line) + 2);
     }
     $body = substr($response, 2);
     $responseObject->setContent($body);
     return $responseObject;
 }