Skip to content

Commit

Permalink
feat(response): Add resource method to retrieve PHP resource
Browse files Browse the repository at this point in the history
- Implement `resource` method in Response class
- Returns the body of the response as a PHP resource
- Uses `StreamWrapper` for resource conversion
  • Loading branch information
guanguans committed Nov 15, 2024
1 parent c266550 commit 402d0f1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Saloon\Helpers\ArrayHelpers;
use Saloon\Helpers\ObjectHelpers;
use Saloon\XmlWrangler\XmlReader;
use GuzzleHttp\Psr7\StreamWrapper;
use Illuminate\Support\Collection;
use Saloon\Contracts\FakeResponse;
use Saloon\Repositories\ArrayStore;
Expand Down Expand Up @@ -299,6 +300,18 @@ public function collect(string|int|null $key = null): Collection
return Collection::make([$data]);
}

/**
* Get the body of the response as a PHP resource.
*
* @return resource
*
* @throws \InvalidArgumentException
*/
public function resource(): mixed
{
return StreamWrapper::getResource($this->stream());
}

/**
* Cast the response to a DTO.
*/
Expand Down
11 changes: 11 additions & 0 deletions tests/Unit/ResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,17 @@
expect($response->collect('age'))->toBeEmpty();
});

test('it can convert the response to a resource', function () {
$mockClient = new MockClient([
MockResponse::make(['foo' => 'bar'], 200, ['Content-Type' => 'application/json;encoding=utf-8']),
]);

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

expect($response->resource())->toBeResource();
expect(stream_get_contents($response->resource()))->toBe($response->body());
});

test('the json method will return empty array if body is empty', function () {
$mockClient = new MockClient([
MockResponse::make('', 404),
Expand Down

0 comments on commit 402d0f1

Please sign in to comment.