class DatabaseStorageExpirable extends DatabaseStorage implements KeyValueStoreExpirableInterface {
protected $connection;
protected $needsGarbageCollection = FALSE;
public function __construct($collection, Connection $connection, $table = 'key_value_expire') {
parent::__construct($collection, $connection, $table);
}
public function __destruct() {
if ($this->needsGarbageCollection) {
$this
->garbageCollection();
}
}
public function getMultiple(array $keys) {
$values = $this->connection
->query('SELECT name, value FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE expire > :now AND name IN (:keys) AND collection = :collection', array(
':now' => REQUEST_TIME,
':keys' => $keys,
':collection' => $this->collection,
))
->fetchAllKeyed();
return array_map('unserialize', $values);
}
public function getAll() {
$values = $this->connection
->query('SELECT name, value FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE collection = :collection AND expire > :now', array(
':collection' => $this->collection,
':now' => REQUEST_TIME,
))
->fetchAllKeyed();
return array_map('unserialize', $values);
}
function setWithExpire($key, $value, $expire) {
$this->needsGarbageCollection = TRUE;
$this->connection
->merge($this->table)
->key(array(
'name' => $key,
'collection' => $this->collection,
))
->fields(array(
'value' => serialize($value),
'expire' => REQUEST_TIME + $expire,
))
->execute();
}
function setWithExpireIfNotExists($key, $value, $expire) {
$this->needsGarbageCollection = TRUE;
$result = $this->connection
->merge($this->table)
->insertFields(array(
'collection' => $this->collection,
'name' => $key,
'value' => serialize($value),
'expire' => REQUEST_TIME + $expire,
))
->condition('collection', $this->collection)
->condition('name', $key)
->execute();
return $result == Merge::STATUS_INSERT;
}
function setMultipleWithExpire(array $data, $expire) {
foreach ($data as $key => $value) {
$this
->setWithExpire($key, $value, $expire);
}
}
public function deleteMultiple(array $keys) {
$this->needsGarbageCollection = TRUE;
parent::deleteMultiple($keys);
}
protected function garbageCollection() {
$this->connection
->delete($this->table)
->condition('expire', REQUEST_TIME, '<')
->execute();
}
}