diff --git a/src/CacheEntry.php b/src/CacheEntry.php index e82dab76..127c1c6e 100644 --- a/src/CacheEntry.php +++ b/src/CacheEntry.php @@ -9,6 +9,7 @@ namespace Kevinrob\GuzzleCache; +use GuzzleHttp\Psr7\Stream; use Psr\Http\Message\ResponseInterface; class CacheEntry @@ -19,6 +20,11 @@ class CacheEntry */ protected $response; + /** + * @var string + */ + protected $responseBody; + /** * @var \DateTime */ @@ -148,4 +154,25 @@ public function hasValidationInformation() return $this->response->hasHeader("Etag") || $this->response->hasHeader("Last-Modified"); } + public function __sleep() + { + if ($this->response !== null) { + $this->responseBody = (string)$this->response->getBody(); + } + + return array_keys(get_object_vars($this)); + } + + public function __wakeup() + { + if ($this->response !== null) { + $stream = fopen('php://memory','r+'); + fwrite($stream, $this->responseBody); + rewind($stream); + + $this->response = $this->response + ->withBody(new Stream($stream)); + } + } + } diff --git a/src/PrivateCache.php b/src/PrivateCache.php index 93273bee..2768d680 100644 --- a/src/PrivateCache.php +++ b/src/PrivateCache.php @@ -47,7 +47,6 @@ protected function getCacheObject(ResponseInterface $response) return $entry->hasValidationInformation() ? $entry : null; } - $matches = []; foreach ($cacheControlDirectives as $directive) { $matches = []; if (preg_match('/^max-age=([0-9]*)$/', $directive, $matches)) { @@ -87,7 +86,7 @@ protected function getCacheKey(RequestInterface $request) public function fetch(RequestInterface $request) { try { - return $this->storage->fetch($this->getCacheKey($request)); + return unserialize($this->storage->fetch($this->getCacheKey($request))); } catch (\Exception $ignored) { return null; } @@ -101,7 +100,7 @@ public function fetch(RequestInterface $request) public function cache(RequestInterface $request, ResponseInterface $response) { try { - return $this->storage->save($this->getCacheKey($request), $this->getCacheObject($response)); + return $this->storage->save($this->getCacheKey($request), serialize($this->getCacheObject($response))); } catch (\Exception $ignored) { return false; }