3
namespace GuzzleHttp\Adapter\Curl;
5
use GuzzleHttp\Adapter\TransactionInterface;
6
use GuzzleHttp\Event\RequestEvents;
7
use GuzzleHttp\Message\MessageFactoryInterface;
8
use GuzzleHttp\Stream\Stream;
9
use GuzzleHttp\Stream\StreamInterface;
12
* Mediator between curl handles and request objects
16
/** @var TransactionInterface */
18
/** @var MessageFactoryInterface */
19
private $messageFactory;
21
private $reasonPhrase;
23
private $protocolVersion;
27
* @param TransactionInterface $transaction Transaction to populate
28
* @param MessageFactoryInterface $messageFactory Creates responses
30
public function __construct(
31
TransactionInterface $transaction,
32
MessageFactoryInterface $messageFactory
34
$this->transaction = $transaction;
35
$this->messageFactory = $messageFactory;
39
* Set the body that will hold the response body
41
* @param StreamInterface $body Response body
43
public function setResponseBody(StreamInterface $body = null)
49
* Receive a response header from curl
51
* @param resource $curl Curl handle
52
* @param string $header Received header
56
public function receiveResponseHeader($curl, $header)
58
static $normalize = ["\r", "\n"];
59
$length = strlen($header);
60
$header = str_replace($normalize, '', $header);
62
if (strpos($header, 'HTTP/') === 0) {
63
$startLine = explode(' ', $header, 3);
64
// Only download the body to a target body when a successful
65
// response is received.
66
if ($startLine[1][0] != '2') {
69
$this->statusCode = $startLine[1];
70
$this->reasonPhrase = isset($startLine[2]) ? $startLine[2] : null;
71
$this->protocolVersion = substr($startLine[0], -3);
73
} elseif ($pos = strpos($header, ':')) {
74
$this->headers[substr($header, 0, $pos)][] = substr($header, $pos + 1);
75
} elseif ($header == '' && $this->statusCode >= 200) {
76
$response = $this->messageFactory->createResponse(
81
'protocol_version' => $this->protocolVersion,
82
'reason_phrase' => $this->reasonPhrase
85
$this->headers = $this->body = null;
86
$this->transaction->setResponse($response);
87
// Allows events to react before downloading any of the body
88
RequestEvents::emitHeaders($this->transaction);
95
* Write data to the response body of a request
97
* @param resource $curl
98
* @param string $write
102
public function writeResponseBody($curl, $write)
104
if (!($response = $this->transaction->getResponse())) {
108
// Add a default body on the response if one was not found
109
if (!($body = $response->getBody())) {
110
$body = new Stream(fopen('php://temp', 'r+'));
111
$response->setBody($body);
114
return $body->write($write);
118
* Read data from the request body and send it to curl
120
* @param resource $ch Curl handle
121
* @param resource $fd File descriptor
122
* @param int $length Amount of data to read
126
public function readRequestBody($ch, $fd, $length)
128
return (string) $this->transaction->getRequest()->getBody()->read($length);