3

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.

thelastshadow
  • 3,406
  • 3
  • 33
  • 36
  • I see that Guzzle has a [CachingStream](https://github.com/guzzle/psr7/blob/master/src/CachingStream.php). Check that code. Maybe it helps. Check [Stream](https://github.com/zendframework/zend-diactoros/blob/master/src/Stream.php) of Zend Diactoros too... _Question_: Would it be a valid solution for you to read the content of your `$stream` as a string and write it in your `$writeHandle`? I might have asked you a wrong question right now, but better to ask than not trying. – PajuranCodes Apr 02 '19 at 03:41
  • Cheers, I'll look at the CachingStream. I could certainly write the string contents to the file - but later in the app's logic flow there's a branch where the url of the cached image is returned rather than the image data, so this way is slightly more efficient for my app. – thelastshadow Apr 02 '19 at 09:39

0 Answers0