Skip to content

Commit 97f2fc4

Browse files
Merge #678
678: Cast body to a string to force rewind of stream r=brunoocasali a=grizzm0 # Pull Request ## What does this PR do? - Rewinds the PSR-7 StreamInterface When reading a PSR-7 StreamInterface with getContents() the stream is not automatically rewound. If you for example attach a middleware in Guzzle that reads the StreamInterface but does not rewind it afterwards any calls afterwards will read from the end of the stream resulting in an empty string. However, then casting the StreamInterface to a string using __toString() then the stream MUST attempt to seek to the beginning of the stream. See https://www.php-fig.org/psr/psr-7/#34-psrhttpmessagestreaminterface Co-authored-by: Kristofer Karlsson <[email protected]>
2 parents ae4f430 + b82d40e commit 97f2fc4

File tree

3 files changed

+5
-5
lines changed

3 files changed

+5
-5
lines changed

src/Http/Client.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,16 +177,16 @@ private function parseResponse(ResponseInterface $response)
177177
}
178178

179179
if (!$this->isJSONResponse($response->getHeader('content-type'))) {
180-
throw new InvalidResponseBodyException($response, $response->getBody()->getContents());
180+
throw new InvalidResponseBodyException($response, (string) $response->getBody());
181181
}
182182

183183
if ($response->getStatusCode() >= 300) {
184-
$body = $this->json->unserialize($response->getBody()->getContents()) ?? $response->getReasonPhrase();
184+
$body = $this->json->unserialize((string) $response->getBody()) ?? $response->getReasonPhrase();
185185

186186
throw new ApiException($response, $body);
187187
}
188188

189-
return $this->json->unserialize($response->getBody()->getContents());
189+
return $this->json->unserialize((string) $response->getBody());
190190
}
191191

192192
/**

tests/Http/ClientTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ private function createHttpClientMock(int $status = 200, string $content = '{',
322322
{
323323
$stream = $this->createMock(StreamInterface::class);
324324
$stream->expects(self::once())
325-
->method('getContents')
325+
->method('__toString')
326326
->willReturn($content);
327327

328328
$response = $this->createMock(ResponseInterface::class);

tests/TestCase.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ protected function createHttpClientMock(int $status = 200, string $content = '{'
153153
{
154154
$stream = $this->createMock(StreamInterface::class);
155155
$stream->expects(self::once())
156-
->method('getContents')
156+
->method('__toString')
157157
->willReturn($content);
158158

159159
$response = $this->createMock(ResponseInterface::class);

0 commit comments

Comments
 (0)