From 606ec5b3f96d15ae679f8ea2b828d1721a05618d Mon Sep 17 00:00:00 2001 From: Muhannad Ajjan Date: Fri, 25 Oct 2024 16:39:51 +0100 Subject: [PATCH] Implement Redis reset() method --- src/Ganesha/Storage/Adapter/Redis.php | 2 +- src/Ganesha/Storage/Adapter/RedisStore.php | 48 ++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/Ganesha/Storage/Adapter/Redis.php b/src/Ganesha/Storage/Adapter/Redis.php index 0bba62e..1bfcc49 100644 --- a/src/Ganesha/Storage/Adapter/Redis.php +++ b/src/Ganesha/Storage/Adapter/Redis.php @@ -146,7 +146,7 @@ public function loadStatus(string $service): int public function reset(): void { - // TODO: Implement reset() method. + $this->redis->reset(); } /** diff --git a/src/Ganesha/Storage/Adapter/RedisStore.php b/src/Ganesha/Storage/Adapter/RedisStore.php index 47f4952..a03e9c4 100644 --- a/src/Ganesha/Storage/Adapter/RedisStore.php +++ b/src/Ganesha/Storage/Adapter/RedisStore.php @@ -3,6 +3,7 @@ namespace Ackintosh\Ganesha\Storage\Adapter; use Ackintosh\Ganesha\Exception\StorageException; +use Ackintosh\Ganesha\Storage; use Exception; class RedisStore @@ -186,4 +187,51 @@ public function get(string $key) throw new StorageException($exception->getMessage(), $exception->getCode(), $exception); } } + + /** + * Resets the storage. + * + * @return void + * + * @throws StorageException + */ + public function reset(): void + { + try { + $redisPrefix = $this->redis->getOption(\Redis::OPT_PREFIX); + $ganeshaPrefix = Storage\StorageKeys::KEY_PREFIX; + $prefix = $redisPrefix . $ganeshaPrefix; + $suffixes = [ + Storage\StorageKeys::KEY_SUFFIX_SUCCESS, + Storage\StorageKeys::KEY_SUFFIX_FAILURE, + Storage\StorageKeys::KEY_SUFFIX_REJECTION, + Storage\StorageKeys::KEY_SUFFIX_LAST_FAILURE_TIME, + Storage\StorageKeys::KEY_SUFFIX_STATUS, + ]; + $suffixesRegex = implode('|', array_map('preg_quote', $suffixes)); + + $iterator = null; + do { + $keys = $this->redis->scan($iterator, $prefix . '*'); + if ($keys !== false) { + $keysToDelete = array_filter(array_map(function ($key) use ($prefix, $redisPrefix, $suffixesRegex) { + return preg_match("/^{$prefix}(.*)(?:$suffixesRegex)$/", $key) ? substr($key, strlen($redisPrefix)) : null; + }, $keys)); + + if (!empty($keysToDelete)) { + $deleted = $this->redis->del($keysToDelete); + if ($deleted !== count($keysToDelete)) { + throw new StorageException(sprintf( + "Failed to delete all keys. Deleted %d out of %d keys.", + $deleted, + count($keysToDelete) + )); + } + } + } + } while ($iterator > 0); + } catch (Exception $exception) { + throw new StorageException($exception->getMessage(), $exception->getCode(), $exception); + } + } }