Skip to content

Commit

Permalink
Fix a bug with cache (serialize)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevinrob committed Jul 17, 2015
1 parent 9100544 commit 1c82e52
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
27 changes: 27 additions & 0 deletions src/CacheEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace Kevinrob\GuzzleCache;


use GuzzleHttp\Psr7\Stream;
use Psr\Http\Message\ResponseInterface;

class CacheEntry
Expand All @@ -19,6 +20,11 @@ class CacheEntry
*/
protected $response;

/**
* @var string
*/
protected $responseBody;

/**
* @var \DateTime
*/
Expand Down Expand Up @@ -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));
}
}

}
5 changes: 2 additions & 3 deletions src/PrivateCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down

0 comments on commit 1c82e52

Please sign in to comment.