Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #205 from Sammyjo20/feature/rewind-stream-when-usi…
…ng-body-method

Fix | Rewinds the body if it is seekable
  • Loading branch information
Sammyjo20 committed Apr 28, 2023
2 parents ed0206e + 42fefcc commit c054777
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
9 changes: 8 additions & 1 deletion src/Http/Response.php
Expand Up @@ -105,7 +105,14 @@ public function getPsrResponse(): ResponseInterface
*/
public function body(): string
{
return (string)$this->stream();
$stream = $this->stream();
$body = $stream->getContents();

if ($stream->isSeekable()) {
$stream->rewind();
}

return $body;
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/Traits/Responses/HasResponseHelpers.php
Expand Up @@ -5,6 +5,7 @@
namespace Saloon\Traits\Responses;

use Throwable;
use LogicException;
use SimpleXMLElement;
use Saloon\Helpers\Arr;
use Illuminate\Support\Collection;
Expand Down Expand Up @@ -143,13 +144,13 @@ public function dto(): mixed
/**
* Convert the response into a DTO or throw a LogicException if the response failed
*
* @throws \LogicException
* @throws LogicException
* @return mixed
*/
public function dtoOrFail(): mixed
{
if ($this->failed()) {
throw new \LogicException('Unable to create data transfer object as the response has failed.', 0, $this->toException());
throw new LogicException('Unable to create data transfer object as the response has failed.', 0, $this->toException());
}

return $this->dto();
Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/SaloonResponseTest.php
Expand Up @@ -238,3 +238,15 @@
expect($response->dom())->toBeInstanceOf(Crawler::class);
expect($response->dom())->toEqual(new Crawler($dom));
});

test('when using the body methods the stream is rewound back to the start', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['X-Custom-Header' => 'Howdy']),
]);

$response = connector()->send(new UserRequest, $mockClient);

expect($response->json())->toEqual(['foo' => 'bar']);
expect($response->body())->toEqual('{"foo":"bar"}');
expect($response->object())->toEqual((object)['foo' => 'bar']);
});

0 comments on commit c054777

Please sign in to comment.