Skip to content

Commit 175a6b1

Browse files
committed
Add saveToFile to the Response class
1 parent 9b86325 commit 175a6b1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/Response.php

+27
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,15 @@
1616
use Exception;
1717
use Http\Promise\Promise;
1818
use function is_array;
19+
use function is_string;
1920
use function json_decode;
2021
use const JSON_THROW_ON_ERROR;
2122
use JsonException;
2223
use Psr\Http\Message\ResponseInterface;
2324
use Psr\Http\Message\StreamInterface;
25+
use SolidWorx\SimpleHttp\Exception\InvalidArgumentException;
2426
use SolidWorx\SimpleHttp\Exception\NotImplementedException;
27+
use function stream_copy_to_stream;
2528

2629
final class Response implements ResponseInterface
2730
{
@@ -176,6 +179,30 @@ public function getReasonPhrase(): string
176179
return $response->getReasonPhrase();
177180
}
178181

182+
/**
183+
* @param string|resource $path
184+
*
185+
* @throws Exception
186+
*/
187+
public function saveToFile($path): void
188+
{
189+
$resource = $path;
190+
191+
if (is_string($path)) {
192+
$resource = fopen($path, 'wb');
193+
}
194+
195+
if (!is_resource($resource)) {
196+
throw new InvalidArgumentException('Invalid path, must be string or resource');
197+
}
198+
199+
$body = $this->getBody()->detach();
200+
201+
if (is_resource($body)) {
202+
stream_copy_to_stream($body, $resource);
203+
}
204+
}
205+
179206
/**
180207
* @throws Exception
181208
*/

0 commit comments

Comments
 (0)