From 55ea884341206e376ed610eb1e2871c043d67b91 Mon Sep 17 00:00:00 2001 From: David Chancogne Date: Fri, 14 Feb 2014 18:15:31 -0500 Subject: [PATCH] Allow multiple key delete support The Redis DEL command allows deletion of multiple keys with a single command. Updated del() function to support multiple keys as well. Keys can be passed as an array of strings or as multiple arguments to the function. --- .gitignore | 1 + src/M6Web/Component/RedisMock/RedisMock.php | 27 ++++++++++++--------- tests/units/RedisMock.php | 16 ++++++------ 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/.gitignore b/.gitignore index d1502b0..164c346 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ vendor/ composer.lock +composer.phar diff --git a/src/M6Web/Component/RedisMock/RedisMock.php b/src/M6Web/Component/RedisMock/RedisMock.php index 5a4a934..9eff446 100644 --- a/src/M6Web/Component/RedisMock/RedisMock.php +++ b/src/M6Web/Component/RedisMock/RedisMock.php @@ -129,23 +129,26 @@ public function exists($key) public function del($key) { - if (func_num_args() > 1) { - throw new UnsupportedException('In RedisMock, `del` command can not remove more than one key at once.'); + if ( is_array($key) ) { + $keys = $key; } - - if (!isset($this->data[$key])) { - return $this->returnPipedInfo(0); + else { + $keys = func_get_args(); } - $deletedItems = count($this->data[$key]); - - unset($this->data[$key]); - unset($this->dataTypes[$key]); - if (array_key_exists($key, $this->dataTtl)) { - unset($this->dataTtl[$key]); + $deletedKeyCount = 0; + foreach ( $keys as $k ) { + if ( isset($this->data[$k]) ) { + $deletedKeyCount += count($this->data[$k]); + unset($this->data[$k]); + unset($this->dataTypes[$k]); + if (array_key_exists($k, $this->dataTtl)) { + unset($this->dataTtl[$k]); + } + } } + return $this->returnPipedInfo($deletedKeyCount); - return $this->returnPipedInfo($deletedItems); } public function keys($pattern) diff --git a/tests/units/RedisMock.php b/tests/units/RedisMock.php index 50652d5..686961f 100644 --- a/tests/units/RedisMock.php +++ b/tests/units/RedisMock.php @@ -41,14 +41,14 @@ public function testSetGetDelExists() ->isEqualTo('OK') ->string($redisMock->set('test2', 'something else')) ->isEqualTo('OK') - ->exception(function() use ($redisMock) { - $redisMock->del('test1', 'test2'); - }) - ->isInstanceOf('\M6Web\Component\RedisMock\UnsupportedException') - ->integer($redisMock->del('test1')) - ->isEqualTo(1) - ->integer($redisMock->del('test2')) - ->isEqualTo(1) + ->integer($redisMock->del('test1', 'test2')) + ->isEqualTo(2) + ->string($redisMock->set('test1', 'something')) + ->isEqualTo('OK') + ->string($redisMock->set('test2', 'something else')) + ->isEqualTo('OK') + ->integer($redisMock->del(array('test1', 'test2'))) + ->isEqualTo(2) ->string($redisMock->set('test', 'something', 1)) ->isEqualTo('OK') ->integer($redisMock->ttl('test'))