Skip to content

[CachePlugin] Streams are not cached #20

Closed
@Nyholm

Description

@Nyholm

I found an issue with the CachePlugin. When we retrieve a Response form the cache we have lost the body because the stream was not in cache.

if ($response->getBody()->__toString() === '') {
  // Always true
}

Im not sure how to solve this in a good way... One solution is to recreate the stream when we fetch the data from cache. This require us to add a dependency on php-http/discovery.

// If we can cache the request
$key = $this->createCacheKey($request);
$cacheItem = $this->pool->getItem($key);

if ($cacheItem->isHit()) {
     // return cached response
     $data = $cacheItem->get();
     $response = $data['response'];
     $response->withBody(StreamFactoryDiscovery::find()->createStream($data['body']));
     return new FulfilledPromise($response);
}

return $next($request)->then(function (ResponseInterface $response) use ($cacheItem) {
     if ($this->isCacheable($response)) {
         $cacheItem->set(['response'=>$response, 'body'=>$response->getBody()->__toString()])
              ->expiresAfter($this->getMaxAge($response));
              $this->pool->save($cacheItem);
      }

      return $response;
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions