View source
<?php
namespace Drupal\Core\KeyValueStore;
use Drupal\Component\Serialization\SerializationInterface;
use Drupal\Core\Database\Connection;
class DatabaseStorageExpirable extends DatabaseStorage implements KeyValueStoreExpirableInterface {
public function __construct($collection, SerializationInterface $serializer, Connection $connection, $table = 'key_value_expire') {
parent::__construct($collection, $serializer, $connection, $table);
}
public function has($key) {
return (bool) $this->connection
->query('SELECT 1 FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE collection = :collection AND name = :key AND expire > :now', [
':collection' => $this->collection,
':key' => $key,
':now' => REQUEST_TIME,
])
->fetchField();
}
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', [
':now' => REQUEST_TIME,
':keys[]' => $keys,
':collection' => $this->collection,
])
->fetchAllKeyed();
return array_map([
$this->serializer,
'decode',
], $values);
}
public function getAll() {
$values = $this->connection
->query('SELECT name, value FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE collection = :collection AND expire > :now', [
':collection' => $this->collection,
':now' => REQUEST_TIME,
])
->fetchAllKeyed();
return array_map([
$this->serializer,
'decode',
], $values);
}
public function setWithExpire($key, $value, $expire) {
$this->connection
->merge($this->table)
->keys([
'name' => $key,
'collection' => $this->collection,
])
->fields([
'value' => $this->serializer
->encode($value),
'expire' => REQUEST_TIME + $expire,
])
->execute();
}
public function setWithExpireIfNotExists($key, $value, $expire) {
if (!$this
->has($key)) {
$this
->setWithExpire($key, $value, $expire);
return TRUE;
}
return FALSE;
}
public function setMultipleWithExpire(array $data, $expire) {
foreach ($data as $key => $value) {
$this
->setWithExpire($key, $value, $expire);
}
}
public function deleteMultiple(array $keys) {
parent::deleteMultiple($keys);
}
}