3 namespace Drupal\Core\KeyValueStore;
5 use Drupal\Component\Serialization\SerializationInterface;
6 use Drupal\Core\Database\Connection;
7 use Drupal\Core\Database\Query\Merge;
10 * Defines a default key/value store implementation for expiring items.
12 * This key/value store implementation uses the database to store key/value
13 * data with an expire date.
15 class DatabaseStorageExpirable extends DatabaseStorage implements KeyValueStoreExpirableInterface {
18 * Overrides Drupal\Core\KeyValueStore\StorageBase::__construct().
20 * @param string $collection
21 * The name of the collection holding key and value pairs.
22 * @param \Drupal\Component\Serialization\SerializationInterface $serializer
23 * The serialization class to use.
24 * @param \Drupal\Core\Database\Connection $connection
25 * The database connection to use.
26 * @param string $table
27 * The name of the SQL table to use, defaults to key_value_expire.
29 public function __construct($collection, SerializationInterface $serializer, Connection $connection, $table = 'key_value_expire') {
30 parent::__construct($collection, $serializer, $connection, $table);
36 public function has($key) {
37 return (bool) $this->connection->query('SELECT 1 FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND name = :key AND expire > :now', [
38 ':collection' => $this->collection,
40 ':now' => REQUEST_TIME,
47 public function getMultiple(array $keys) {
48 $values = $this->connection->query(
49 'SELECT name, value FROM {' . $this->connection->escapeTable($this->table) . '} WHERE expire > :now AND name IN ( :keys[] ) AND collection = :collection',
51 ':now' => REQUEST_TIME,
53 ':collection' => $this->collection,
55 return array_map([$this->serializer, 'decode'], $values);
61 public function getAll() {
62 $values = $this->connection->query(
63 'SELECT name, value FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND expire > :now',
65 ':collection' => $this->collection,
66 ':now' => REQUEST_TIME
68 return array_map([$this->serializer, 'decode'], $values);
74 public function setWithExpire($key, $value, $expire) {
75 $this->connection->merge($this->table)
78 'collection' => $this->collection,
81 'value' => $this->serializer->encode($value),
82 'expire' => REQUEST_TIME + $expire,
90 public function setWithExpireIfNotExists($key, $value, $expire) {
91 $result = $this->connection->merge($this->table)
93 'collection' => $this->collection,
95 'value' => $this->serializer->encode($value),
96 'expire' => REQUEST_TIME + $expire,
98 ->condition('collection', $this->collection)
99 ->condition('name', $key)
101 return $result == Merge::STATUS_INSERT;
107 public function setMultipleWithExpire(array $data, $expire) {
108 foreach ($data as $key => $value) {
109 $this->setWithExpire($key, $value, $expire);
116 public function deleteMultiple(array $keys) {
117 parent::deleteMultiple($keys);