Skip to content

Commit b1de794

Browse files
author
Kyra Farrow
committed
[HttpClient] fix canceling responses in a streaming loop
1 parent 28b9ac7 commit b1de794

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

Response/MockResponse.php

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,15 @@ public function getInfo(string $type = null)
7878
return null !== $type ? $this->info[$type] ?? null : $this->info;
7979
}
8080

81+
/**
82+
* {@inheritdoc}
83+
*/
84+
public function cancel(): void
85+
{
86+
$this->info['error'] = 'Response has been canceled.';
87+
$this->body = null;
88+
}
89+
8190
/**
8291
* {@inheritdoc}
8392
*/
@@ -150,8 +159,11 @@ protected static function perform(ClientState $multi, array &$responses): void
150159
foreach ($responses as $response) {
151160
$id = $response->id;
152161

153-
if (!$response->body) {
154-
// Last chunk
162+
if (null === $response->body) {
163+
// Canceled response
164+
$response->body = [];
165+
} elseif ([] === $response->body) {
166+
// Error chunk
155167
$multi->handlesActivity[$id][] = null;
156168
$multi->handlesActivity[$id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
157169
} elseif (null === $chunk = array_shift($response->body)) {
@@ -242,7 +254,7 @@ private static function readResponse(self $response, array $options, ResponseInt
242254

243255
// populate info related to headers
244256
$info = $mock->getInfo() ?: [];
245-
$response->info['http_code'] = ($info['http_code'] ?? 0) ?: $mock->getStatusCode(false) ?: 200;
257+
$response->info['http_code'] = ($info['http_code'] ?? 0) ?: $mock->getStatusCode() ?: 200;
246258
$response->addResponseHeaders($info['response_headers'] ?? [], $response->info, $response->headers);
247259
$dlSize = isset($response->headers['content-encoding']) ? 0 : (int) ($response->headers['content-length'][0] ?? 0);
248260

Response/ResponseTrait.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ public static function stream(iterable $responses, float $timeout = null): \Gene
327327

328328
unset($multi->handlesActivity[$j]);
329329

330-
if ($chunk instanceof FirstChunk && null === $response->initializer) {
330+
if ($chunk instanceof FirstChunk && null === $response->initializer && null === $response->info['error']) {
331331
// Ensure the HTTP status code is always checked
332332
$response->getHeaders(true);
333333
} elseif ($chunk instanceof ErrorChunk && !$chunk->didThrow()) {

0 commit comments

Comments
 (0)