3 namespace Drupal\Core\State;
5 use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
8 * Provides the state system using a key value store.
10 class State implements StateInterface {
13 * The key value store to use.
15 * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
17 protected $keyValueStore;
24 protected $cache = [];
27 * Constructs a State object.
29 * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
30 * The key value store to use.
32 public function __construct(KeyValueFactoryInterface $key_value_factory) {
33 $this->keyValueStore = $key_value_factory->get('state');
39 public function get($key, $default = NULL) {
40 $values = $this->getMultiple([$key]);
41 return isset($values[$key]) ? $values[$key] : $default;
47 public function getMultiple(array $keys) {
50 foreach ($keys as $key) {
51 // Check if we have a value in the cache.
52 if (isset($this->cache[$key])) {
53 $values[$key] = $this->cache[$key];
55 // Load the value if we don't have an explicit NULL value.
56 elseif (!array_key_exists($key, $this->cache)) {
62 $loaded_values = $this->keyValueStore->getMultiple($load);
63 foreach ($load as $key) {
64 // If we find a value, even one that is NULL, add it to the cache and
66 if (isset($loaded_values[$key]) || array_key_exists($key, $loaded_values)) {
67 $values[$key] = $loaded_values[$key];
68 $this->cache[$key] = $loaded_values[$key];
71 $this->cache[$key] = NULL;
82 public function set($key, $value) {
83 $this->cache[$key] = $value;
84 $this->keyValueStore->set($key, $value);
90 public function setMultiple(array $data) {
91 foreach ($data as $key => $value) {
92 $this->cache[$key] = $value;
94 $this->keyValueStore->setMultiple($data);
100 public function delete($key) {
101 $this->deleteMultiple([$key]);
107 public function deleteMultiple(array $keys) {
108 foreach ($keys as $key) {
109 unset($this->cache[$key]);
111 $this->keyValueStore->deleteMultiple($keys);
117 public function resetCache() {