Fix #17710: Fix MemCache duration normalization to avoid memcached/system timestamp mismatch

This commit is contained in:
Alexander Makarov
2019-12-12 23:07:10 +03:00
committed by GitHub
parent 89814e624f
commit 3b6668804c
2 changed files with 28 additions and 14 deletions

View File

@ -292,11 +292,7 @@ class MemCache extends Cache
*/
protected function setValue($key, $value, $duration)
{
// Use UNIX timestamp since it doesn't have any limitation
// @see https://secure.php.net/manual/en/memcache.set.php
// @see https://secure.php.net/manual/en/memcached.expiration.php
$expire = $duration > 0 ? $duration + time() : 0;
$expire = $this->normalizeDuration($duration);
return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
}
@ -309,10 +305,7 @@ class MemCache extends Cache
protected function setValues($data, $duration)
{
if ($this->useMemcached) {
// Use UNIX timestamp since it doesn't have any limitation
// @see https://secure.php.net/manual/en/memcache.set.php
// @see https://secure.php.net/manual/en/memcached.expiration.php
$expire = $duration > 0 ? $duration + time() : 0;
$expire = $this->normalizeDuration($duration);
// Memcached::setMulti() returns boolean
// @see https://secure.php.net/manual/en/memcached.setmulti.php
@ -334,11 +327,7 @@ class MemCache extends Cache
*/
protected function addValue($key, $value, $duration)
{
// Use UNIX timestamp since it doesn't have any limitation
// @see https://secure.php.net/manual/en/memcache.set.php
// @see https://secure.php.net/manual/en/memcached.expiration.php
$expire = $duration > 0 ? $duration + time() : 0;
$expire = $this->normalizeDuration($duration);
return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
}
@ -362,4 +351,28 @@ class MemCache extends Cache
{
return $this->_cache->flush();
}
/**
* Normalizes duration value
*
* @see https://github.com/yiisoft/yii2/issues/17710
* @see https://secure.php.net/manual/en/memcache.set.php
* @see https://secure.php.net/manual/en/memcached.expiration.php
*
* @since 2.0.31
* @param int $duration
* @return int
*/
protected function normalizeDuration($duration)
{
if ($duration < 0) {
return 0;
}
if ($duration < 2592001) {
return $duration;
}
return $duration + time();
}
}