Skip to content

Commit

Permalink
feat(response): Add resource method to retrieve response body
Browse files Browse the repository at this point in the history
- Introduce `resource` method in `Response` class to access the body as a PHP resource.
- Utilize `StreamWrapper` from GuzzleHttp to facilitate resource retrieval.
- Enhance functionality for better integration with resource handling in PHP.
  • Loading branch information
guanguans committed Nov 14, 2024
1 parent aedbef8 commit 27d2b2f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer-require-checker.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"GuzzleHttp\\Psr7\\Message",
"GuzzleHttp\\Psr7\\MultipartStream",
"GuzzleHttp\\Psr7\\Response",
"GuzzleHttp\\Psr7\\StreamWrapper",
"GuzzleHttp\\Psr7\\Utils",
"Illuminate\\Support\\Collection",
"PhpParser\\Node",
Expand Down
13 changes: 13 additions & 0 deletions src/Foundation/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Guanguans\Notify\Foundation\Support\Arr;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Psr7\Message;
use GuzzleHttp\Psr7\StreamWrapper;
use GuzzleHttp\TransferStats;
use Illuminate\Support\Collection;
use Psr\Http\Message\RequestInterface;
Expand Down Expand Up @@ -200,6 +201,18 @@ public function collect($key = null): Collection
return Collection::make($this->json($key));
}

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

/**
* Generate a data URL from the content type and body.
*/
Expand Down
12 changes: 12 additions & 0 deletions tests/Foundation/ResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,18 @@
)->toBeInstanceOf(Collection::class);
})->group(__DIR__, __FILE__);

it('can convert to resource', function (): void {
expect(
Response::fromPsrResponse(
new \GuzzleHttp\Psr7\Response(
200,
[],
json_encode(['foo' => 'bar'], \JSON_THROW_ON_ERROR),
),
)->resource(),
)->toBeResource();
})->group(__DIR__, __FILE__);

it('can convert to data url', function (): void {
expect(
Response::fromPsrResponse(
Expand Down

0 comments on commit 27d2b2f

Please sign in to comment.