Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Commit

Permalink
Merge pull request #40 from jbottigliero/hotfix/Redis.internalAddItem…
Browse files Browse the repository at this point in the history
…-TTL

hotfix : Redis.addItem TTL
  • Loading branch information
marc-mabe committed Nov 6, 2015
2 parents d2eb400 + 7bf6be9 commit a9668fc
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Storage/Adapter/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,25 @@ protected function internalSetItems(array & $normalizedKeyValuePairs)
protected function internalAddItem(& $normalizedKey, & $value)
{
$redis = $this->getRedisResource();
$ttl = $this->getOptions()->getTtl();

try {
return $redis->setnx($this->namespacePrefix . $normalizedKey, $value);
if ($ttl) {
if ($this->resourceManager->getMajorVersion($this->resourceId) < 2) {
throw new Exception\UnsupportedMethodCallException("To use ttl you need version >= 2.0.0");
}
/**
* To ensure expected behaviour, we stick with the "setnx" method.
* This means we only set the ttl after the key/value has been successfully set.
*/
$success = $redis->setnx($this->namespacePrefix . $normalizedKey, $value);
if ($success) {
$redis->expire($this->namespacePrefix . $normalizedKey, $ttl);
}
} else {
$success = $redis->setnx($this->namespacePrefix . $normalizedKey, $value);
}
return $success;
} catch (RedisResourceException $e) {
throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e);
}
Expand Down
26 changes: 26 additions & 0 deletions test/Storage/Adapter/CommonAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,32 @@ public function testAddItemsReturnsFailedKeys()
$this->assertTrue($this->_storage->hasItem('key2'));
}

public function testAddItemSetsTTL()
{
$capabilities = $this->_storage->getCapabilities();

if ($capabilities->getMinTtl() === 0) {
$this->markTestSkipped("Adapter doesn't support item expiration");
}

$ttl = $capabilities->getTtlPrecision();
$this->_options->setTtl($ttl);

$this->waitForFullSecond();

$this->assertTrue($this->_storage->addItem('key', 'value'));

// wait until the item expired
$wait = $ttl + $capabilities->getTtlPrecision();
usleep($wait * 2000000);

if (!$capabilities->getUseRequestTime()) {
$this->assertFalse($this->_storage->hasItem('key'));
} else {
$this->assertTrue($this->_storage->hasItem('key'));
}
}

public function testReplaceExistingItem()
{
$this->assertTrue($this->_storage->setItem('key', 'value'));
Expand Down

0 comments on commit a9668fc

Please sign in to comment.