Skip to content

Commit

Permalink
Don't use flushdb when clearing the cache
Browse files Browse the repository at this point in the history
Some systems will have FLUSHDB disabled and this also makes it easier to share a database between applications without flushing all cache if cache key prefixes are used.
  • Loading branch information
freost committed Nov 4, 2024
1 parent 9ae5d70 commit 932eafd
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1752,6 +1752,7 @@ The major version bump is due to dropped support for PHP `7.0` and `7.1` and a s
* Removed support for "piped" validation rules.
* New syntax for passing parameters to middleware.
* New syntax for passing parameters to validation rules.
* The Redis cache `clear` implementation will no longer flush the entire database but instead just deleted the cached keys.

#### Bugfixes

Expand Down
11 changes: 10 additions & 1 deletion src/mako/cache/stores/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use mako\redis\Redis as RedisClient;

use function array_chunk;
use function is_numeric;
use function serialize;
use function unserialize;
Expand Down Expand Up @@ -112,6 +113,14 @@ public function remove(string $key): bool
*/
public function clear(): bool
{
return (bool) $this->redis->flushdb();
$keys = $this->redis->keys($this->getPrefixedKey('*'));

if (!empty($keys)) {
foreach (array_chunk($keys, 100) as $chunk) {
$this->redis->del(...$chunk);
}
}

return true;
}
}
22 changes: 21 additions & 1 deletion tests/unit/cache/stores/RedisTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,10 +298,30 @@ public function testClear(): void
{
$client = $this->getRedisClient();

$client->shouldReceive('flushdb')->once();
$client->shouldReceive('keys')->once()->with('*')->andReturn(['foo', 'bar']);

$client->shouldReceive('del')->once()->with('foo', 'bar')->andReturn(2);

$redis = new Redis($client);

$redis->clear();
}

/**
*
*/
public function testClearWithPrefix(): void
{
$client = $this->getRedisClient();

$client->shouldReceive('keys')->once()->with('prefix.*')->andReturn(['prefix.foo', 'prefix.bar']);

$client->shouldReceive('del')->once()->with('prefix.foo', 'prefix.bar')->andReturn(2);

$redis = new Redis($client);

$redis->setPrefix('prefix');

$redis->clear();
}
}

0 comments on commit 932eafd

Please sign in to comment.