Skip to content

Commit

Permalink
Merge pull request #67 from gm-ghanover/feature/setOptions
Browse files Browse the repository at this point in the history
Update SET to take timeout or options array
  • Loading branch information
omansour authored Aug 7, 2019
2 parents 61a517e + 343e1c2 commit 3f308e4
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/M6Web/Component/RedisMock/RedisMock.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down
31 changes: 31 additions & 0 deletions tests/units/RedisMock.php
Original file line number Diff line number Diff line change
Expand Up @@ -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')))
Expand Down

0 comments on commit 3f308e4

Please sign in to comment.