Skip to content

Commit

Permalink
Merge #678
Browse files Browse the repository at this point in the history
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 <karlsson.kristofer@gmail.com>
  • Loading branch information
meili-bors[bot] and grizzm0 authored Sep 15, 2024
2 parents ae4f430 + b82d40e commit 97f2fc4
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/Http/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,16 +177,16 @@ private function parseResponse(ResponseInterface $response)
}

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

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

throw new ApiException($response, $body);
}

return $this->json->unserialize($response->getBody()->getContents());
return $this->json->unserialize((string) $response->getBody());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/Http/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ private function createHttpClientMock(int $status = 200, string $content = '{',
{
$stream = $this->createMock(StreamInterface::class);
$stream->expects(self::once())
->method('getContents')
->method('__toString')
->willReturn($content);

$response = $this->createMock(ResponseInterface::class);
Expand Down
2 changes: 1 addition & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ protected function createHttpClientMock(int $status = 200, string $content = '{'
{
$stream = $this->createMock(StreamInterface::class);
$stream->expects(self::once())
->method('getContents')
->method('__toString')
->willReturn($content);

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

0 comments on commit 97f2fc4

Please sign in to comment.