diff --git a/src/M6Web/Component/RedisMock/RedisMock.php b/src/M6Web/Component/RedisMock/RedisMock.php index 8d36339..69f8e5a 100644 --- a/src/M6Web/Component/RedisMock/RedisMock.php +++ b/src/M6Web/Component/RedisMock/RedisMock.php @@ -79,6 +79,29 @@ public function get($key) public function set($key, $value, $seconds = null) { + if (\is_array($seconds)) { + /** + * Per https://redis.io/commands/set#options + * EX seconds -- Set the specified expire time, in seconds. + * PX milliseconds -- Set the specified expire time, in milliseconds. + * NX -- Only set the key if it does not already exist. + * XX -- Only set the key if it already exist. + */ + $options = $seconds; + if (\in_array('nx', $options, true) && $this->get($key)) { + return $this->returnPipedInfo(0); + } + if (\in_array('xx', $options, true) && !$this->get($key)) { + return $this->returnPipedInfo(0); + } + + $seconds = null; + if (isset($options['ex'])) { + $seconds = $options['ex']; + } elseif (isset($options['px'])) { + $seconds = $options['px'] / 1000; + } + } self::$dataValues[$this->storage][$key] = $value; self::$dataTypes[$this->storage][$key] = 'string'; diff --git a/tests/units/RedisMock.php b/tests/units/RedisMock.php index ef579dd..e77c09e 100644 --- a/tests/units/RedisMock.php +++ b/tests/units/RedisMock.php @@ -129,6 +129,37 @@ public function testSetGetDelExists() ->integer($redisMock->setnx("test-setnx-expire", "lala")) ->isEqualTo(1); + //set with nx + $this->assert + ->string($redisMock->set('test-set-nx', 'value', ['nx'])) + ->isEqualTo('OK'); + $this->assert + ->integer($redisMock->set('test-set-nx', 'value', ['nx'])) + ->isEqualTo(0); + + //set with xx + $this->assert + ->integer($redisMock->set('test-set-xx', 'value', ['xx'])) + ->isEqualTo(0); + $this->assert + ->string($redisMock->set('test-set-xx', 'value')) + ->isEqualTo('OK'); + $this->assert + ->string($redisMock->set('test-set-xx', 'value2', ['xx'])) + ->isEqualTo('OK'); + + //set with nx ex + $this->assert + ->string($redisMock->set('test-set-nx-ex', 'value', ['nx', 'ex' => 1])) + ->isEqualTo('OK'); + $this->assert + ->integer($redisMock->set('test-set-nx-ex', 'value', ['nx', 'ex' => 1])) + ->isEqualTo(0); + sleep(2); + $this->assert + ->integer($redisMock->exists('test-set-nx-ex')) + ->isEqualTo(0); + //mget/mset test (roughly based on hmset/hmset tests) $this->assert ->array($redisMock->mget(array('raoul', 'test1')))