diff --git a/.gitignore b/.gitignore index 559bf76..bd0adc3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ vendor # project index.php +package.json +node_modules \ No newline at end of file diff --git a/README.md b/README.md index 6356f55..f925d76 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,12 @@ $client->put('redis', '127.0.0.1:6579', ['lease' => 7587822882194199413]); // get key value $client->get('redis'); +// get all keys +$client->getAllKeys(); + +// get keys with prefix +$client->getKeysWithPrefix('/v3/service/user/'); + // delete key $client->del('redis'); diff --git a/src/Client.php b/src/Client.php index 6653687..977960b 100644 --- a/src/Client.php +++ b/src/Client.php @@ -186,6 +186,37 @@ public function get($key, array $options = []) return $body; } + /** + * get all keys + * + * @return array|\GuzzleHttp\Exception\BadResponseException + */ + public function getAllKeys() + { + return $this->get("\0", ['range_end' => "\0"]); + } + + /** + * get all keys with prefix + * + * @param string $prefix + * @return array|\GuzzleHttp\Exception\BadResponseException + */ + public function getKeysWithPrefix($prefix) + { + $prefix = trim($prefix); + if (!$prefix) { + return []; + } + $lastIndex = strlen($prefix) - 1; + $lastChar = $prefix[$lastIndex]; + $nextAsciiCode = ord($lastChar) + 1; + $rangeEnd = $prefix; + $rangeEnd[$lastIndex] = chr($nextAsciiCode); + + return $this->get($prefix, ['range_end' => $rangeEnd]); + } + /** * Removes the specified key or range of keys * diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 201ad06..e78d314 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -36,6 +36,18 @@ public function testPutAndRange() $this->assertEquals($value, $body[$this->key]); } + public function testGetAllKeys() + { + $body = $this->client->getAllKeys(); + $this->assertNotEmpty($body); + } + + public function testGetKeysWithPrefix() + { + $body = $this->client->getKeysWithPrefix('/'); + $this->assertNotEmpty($body); + } + public function testDeleteRange() { $this->client->del($this->key);