From 402d0f18f285c5bd91779b131d2fbb15ce6172a8 Mon Sep 17 00:00:00 2001 From: guanguans Date: Fri, 15 Nov 2024 13:05:24 +0800 Subject: [PATCH] feat(response): Add resource method to retrieve PHP resource - Implement `resource` method in Response class - Returns the body of the response as a PHP resource - Uses `StreamWrapper` for resource conversion --- src/Http/Response.php | 13 +++++++++++++ tests/Unit/ResponseTest.php | 11 +++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/Http/Response.php b/src/Http/Response.php index bc2ed81b..d43d9df2 100644 --- a/src/Http/Response.php +++ b/src/Http/Response.php @@ -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; @@ -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. */ diff --git a/tests/Unit/ResponseTest.php b/tests/Unit/ResponseTest.php index e63878d4..5eef4170 100644 --- a/tests/Unit/ResponseTest.php +++ b/tests/Unit/ResponseTest.php @@ -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),