View source
<?php
namespace Drupal\Core\KeyValueStore;
use Drupal\Component\Serialization\SerializationInterface;
use Drupal\Core\Database\Query\Merge;
use Drupal\Core\Database\Connection;
class DatabaseStorage extends StorageBase {
protected $serializer;
protected $connection;
protected $table;
public function __construct($collection, SerializationInterface $serializer, Connection $connection, $table = 'key_value') {
parent::__construct($collection);
$this->serializer = $serializer;
$this->connection = $connection;
$this->table = $table;
}
public function has($key) {
return (bool) $this->connection
->query('SELECT 1 FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE collection = :collection AND name = :key', array(
':collection' => $this->collection,
':key' => $key,
))
->fetchField();
}
public function getMultiple(array $keys) {
$values = array();
try {
$result = $this->connection
->query('SELECT name, value FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE name IN (:keys) AND collection = :collection', array(
':keys' => $keys,
':collection' => $this->collection,
))
->fetchAllAssoc('name');
foreach ($keys as $key) {
if (isset($result[$key])) {
$values[$key] = $this->serializer
->decode($result[$key]->value);
}
}
} catch (\Exception $e) {
}
return $values;
}
public function getAll() {
$result = $this->connection
->query('SELECT name, value FROM {' . $this->connection
->escapeTable($this->table) . '} WHERE collection = :collection', array(
':collection' => $this->collection,
));
$values = array();
foreach ($result as $item) {
if ($item) {
$values[$item->name] = $this->serializer
->decode($item->value);
}
}
return $values;
}
public function set($key, $value) {
$this->connection
->merge($this->table)
->key(array(
'name' => $key,
'collection' => $this->collection,
))
->fields(array(
'value' => $this->serializer
->encode($value),
))
->execute();
}
public function setIfNotExists($key, $value) {
$result = $this->connection
->merge($this->table)
->insertFields(array(
'collection' => $this->collection,
'name' => $key,
'value' => $this->serializer
->encode($value),
))
->condition('collection', $this->collection)
->condition('name', $key)
->execute();
return $result == Merge::STATUS_INSERT;
}
public function rename($key, $new_key) {
$this->connection
->update($this->table)
->fields(array(
'name' => $new_key,
))
->condition('collection', $this->collection)
->condition('name', $key)
->execute();
}
public function deleteMultiple(array $keys) {
while ($keys) {
$this->connection
->delete($this->table)
->condition('name', array_splice($keys, 0, 1000), 'IN')
->condition('collection', $this->collection)
->execute();
}
}
public function deleteAll() {
$this->connection
->delete($this->table)
->condition('collection', $this->collection)
->execute();
}
}