phplibrary/src/Connection/HttpResponse.php

87 lines
2.1 KiB
PHP

<?php
/**
* Обрабатывает HTTP ответ
*/
namespace ctiso\Connection;
class HttpResponse
{
private $offset;
private $param = [];
private $code;
public $response;
public $version;
public $data;
public function __construct($response)
{
$this->offset = 0;
$this->response = $response;
$this->parseMessage();
}
/**
* Обработка HTTP ответа
*/
private function parseMessage()
{
$http = explode(" ", $this->getLine());
$this->version = $http[0];
$this->code = $http[1];
$line = $this->getLine();
while ($offset = strpos($line, ":")) {
$this->param[substr($line, 0, $offset)] = trim(substr($line, $offset + 1));
$line = $this->getLine();
}
if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') {
//$this->data = substr($this->response, $this->offset);
$index = hexdec($this->getLine());
$chunk = [];
while ($index > 0) {
$chunk [] = substr($this->response, $this->offset, $index);
$this->offset += $index;
$index = hexdec($this->getLine());
}
$this->data = implode("", $chunk);
} else {
$this->data = substr($this->response, $this->offset);
}
}
/**
* Обработка строки HTTP ответа
*/
private function getLine()
{
$begin = $this->offset;
$offset = strpos($this->response, "\r\n", $this->offset);
$result = substr($this->response, $begin, $offset - $begin);
$this->offset = $offset + 2;
return $result;
}
/**
* Значение параметра HTTP ответа
*/
public function getParameter($name)
{
return $this->param[$name];
}
public function getData()
{
return $this->data;
}
/**
* Состояние
*/
public function getCode()
{
return $this->code;
}
}