Skip to content

Commit

Permalink
serialize data before writing it to redis
Browse files Browse the repository at this point in the history
  • Loading branch information
dakorpar authored and f3l1x committed Dec 17, 2020
1 parent 615f67c commit 95e324e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ tests: vendor

coverage: vendor
vendor/bin/tester -s -p phpdbg --colors 1 -C --coverage ./coverage.xml --coverage-src ./src tests/cases

coverage-html:
vendor/bin/tester -s -p phpdbg --colors 1 -C --coverage ./coverage.html --coverage-src ./src tests/cases
20 changes: 12 additions & 8 deletions src/Caching/RedisStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use Nette\Caching\Cache;
use Nette\Caching\IStorage;
use Predis\Client;
use Throwable;

final class RedisStorage implements IStorage
{
Expand All @@ -29,12 +28,12 @@ public function getClient(): Client
*/
public function write(string $key, $data, array $dependencies): void
{
$this->client->set($key, $data);
$this->client->set($key, serialize($data));

if (isset($dependencies[Cache::EXPIRATION])) {
$expiration = (int) $dependencies[Cache::EXPIRATION];

if ($dependencies[Cache::SLIDING] !== true) {
if (!isset($dependencies[Cache::SLIDING]) || $dependencies[Cache::SLIDING] !== true) {
$this->client->expireat($key, time() + $expiration);
} else {
$this->client->expire($key, $expiration);
Expand All @@ -44,17 +43,22 @@ public function write(string $key, $data, array $dependencies): void

/**
* @return mixed
* @phpcsSuppress SlevomatCodingStandard.TypeHints.TypeHintDeclaration.MissingParameterTypeHint
*/
public function read(string $key)
{
$val = $this->client->get($key);
$serializedValue = $this->client->get($key);

try {
return $val;
} catch (Throwable $e) {
if ($serializedValue === null) {
return null;
}

if ($serializedValue === 'b:0;') {
return false;
}

$value = @unserialize($serializedValue);

return $value === false ? null : $value;
}

public function lock(string $key): void
Expand Down
6 changes: 5 additions & 1 deletion tests/cases/RedisStorage.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use Tester\Assert;
require_once __DIR__ . '/../bootstrap.php';

test(function (): void {
$storage = (object) [];
$storage = (object) ['unserialized' => 'unserialized'];

$conn = Mockery::mock(ConnectionInterface::class)
->shouldReceive('executeCommand')
Expand All @@ -36,4 +36,8 @@ test(function (): void {
Assert::same('bat', $redis->read('foo'));
$redis->remove('foo');
Assert::null($redis->read('foo'));
Assert::null($redis->read('unserialized'));

$redis->write('false', false, []);
Assert::false($redis->read('false'));
});

0 comments on commit 95e324e

Please sign in to comment.