From 2f35c41aa3db404880b13edd84428303a2563277 Mon Sep 17 00:00:00 2001 From: Einar Hansen <49709354+einar-hansen@users.noreply.github.com> Date: Wed, 7 Aug 2024 09:54:23 +0200 Subject: [PATCH] Add resource method to Illuminate\Http\Client\Response --- src/Illuminate/Http/Client/Response.php | 14 ++++++++++++++ tests/Http/HttpClientTest.php | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/Illuminate/Http/Client/Response.php b/src/Illuminate/Http/Client/Response.php index fce149edc7ec..38281c5c9cee 100644 --- a/src/Illuminate/Http/Client/Response.php +++ b/src/Illuminate/Http/Client/Response.php @@ -3,6 +3,7 @@ namespace Illuminate\Http\Client; use ArrayAccess; +use GuzzleHttp\Psr7\StreamWrapper; use Illuminate\Support\Collection; use Illuminate\Support\Traits\Macroable; use LogicException; @@ -107,6 +108,19 @@ public function collect($key = null) return Collection::make($this->json($key)); } + /** + * Get the body of the response as a php resource. + * + * @param string|null $key + * @return resource + * + * @throws \InvalidArgumentException if stream is not readable or writable + */ + public function resource() + { + return StreamWrapper::getResource($this->response->getBody()); + } + /** * Get a header from the response. * diff --git a/tests/Http/HttpClientTest.php b/tests/Http/HttpClientTest.php index 1833fbd4bbe0..cac007d72473 100644 --- a/tests/Http/HttpClientTest.php +++ b/tests/Http/HttpClientTest.php @@ -327,6 +327,18 @@ public function testResponseObjectAsObject() $this->assertSame('bar', $response->object()->result->foo); } + public function testResponseCanBeReturnedAsResource() + { + $this->factory->fake([ + '*' => ['result' => ['foo' => 'bar']], + ]); + + $response = $this->factory->get('http://foo.com/api'); + + $this->assertIsResource($response->resource()); + $this->assertSame('{"result":{"foo":"bar"}}', stream_get_contents($response->resource())); + } + public function testResponseCanBeReturnedAsCollection() { $this->factory->fake([