I'm building a read-through image cache and I'm looking for a way to write PSR-7 streams to files on the server. The documentation isn't wonderfully clear on how to do this (it mostly focuses on serving files, rather than writing them).
My current best effort uses $stream->detach()
which isn't ideal (as it destroys the underlying stream, which I then cannot return to the user). Is there a better way to do this?
/* @var GuzzleHttp\Client $httpClient */
$response = $httpClient->request(
'GET', 'https://example.com/image.png'
);
// Validate response, etc.
$stream = $response->getBody();
$stream->isReadable(); // now true
$cachePath = '/path/to/local/cache/unique-name.png';
$writeHandle = fopen($cachePath, 'w');
stream_copy_to_stream($stream->detach(), $writeHandle);
$stream->isReadable(); // now false due to detach()
// To serve the data I'd need to create a new stream
// from the image I've just created
return new GuzzleHttp\Psr7\Stream(fopen($cachePath, 'rb'))
To preempt all the 'why are you doing this' questions; I'm getting these images from a remote service. The terms of that service requires me to cache images locally.