public function cas($token, $key, $value, $expire = 0)
{
$ttl = $this->ttl($expire);
// lock required because we can't perform an atomic CAS
if (!$this->lock($key)) {
return false;
}
// check for values that were just stored in this request but have
// actually expired by now
if (isset($this->expires[$key]) && $this->expires[$key] < time()) {
return false;
}
// get current value, to compare with token
$compare = $this->apcu_fetch($key);
if ($compare === false) {
$this->unlock($key);
return false;
}
if ($token !== serialize($compare)) {
$this->unlock($key);
return false;
}
// negative TTLs don't always seem to properly treat the key as deleted
if ($ttl < 0) {
$this->apcu_delete($key);
unset($this->expires[$key]);
$this->unlock($key);
return true;
}
$success = $this->apcu_store($key, $value, $ttl);
$this->expire($key, $ttl);
$this->unlock($key);
return $success;
}