Skip to content

Commit 963c535

Browse files
committed
feat(Response): Add stream method to retrieve body as stream
- Implement new stream method in Response class - Allow retrieval of the response body as a stream interface - Ensure stream is seekable and rewound before return - Enhance body handling for easier manipulation of response content
1 parent adf3007 commit 963c535

1 file changed

Lines changed: 24 additions & 13 deletions

File tree

src/Foundation/Response.php

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
use Illuminate\Support\Collection;
2727
use Psr\Http\Message\RequestInterface;
2828
use Psr\Http\Message\ResponseInterface;
29+
use Psr\Http\Message\StreamInterface;
2930
use Psr\Http\Message\UriInterface;
3031

3132
/**
@@ -196,6 +197,28 @@ public function collect($key = null): Collection
196197
return Collection::make($this->json($key));
197198
}
198199

200+
/**
201+
* Generate a data URL from the content type and body.
202+
*/
203+
public function dataUrl(): string
204+
{
205+
return \sprintf('data:%s;base64,%s', $this->getHeaderLine('Content-Type'), base64_encode($this->body()));
206+
}
207+
208+
/**
209+
* Get the body as a stream.
210+
*/
211+
public function stream(): StreamInterface
212+
{
213+
$stream = $this->getBody();
214+
215+
if ($stream->isSeekable()) {
216+
$stream->rewind();
217+
}
218+
219+
return $stream;
220+
}
221+
199222
/**
200223
* Get the body of the response as a PHP resource.
201224
*
@@ -208,14 +231,6 @@ public function resource()
208231
return StreamWrapper::getResource($this->getBody());
209232
}
210233

211-
/**
212-
* Generate a data URL from the content type and body.
213-
*/
214-
public function dataUrl(): string
215-
{
216-
return \sprintf('data:%s;base64,%s', $this->getHeaderLine('Content-Type'), base64_encode($this->body()));
217-
}
218-
219234
/**
220235
* Save the response to resource or file.
221236
*
@@ -235,11 +250,7 @@ public function saveAs($resourceOrPath, bool $closeResource = true): void
235250

236251
rewind($resource);
237252

238-
$stream = $this->getBody();
239-
240-
if ($stream->isSeekable()) {
241-
$stream->rewind();
242-
}
253+
$stream = $this->stream();
243254

244255
while (!$stream->eof()) {
245256
fwrite($resource, $stream->read(1024));

0 commit comments

Comments
 (0)