State.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Drupal\Core\State;
  3. use Drupal\Core\Cache\CacheBackendInterface;
  4. use Drupal\Core\Cache\CacheCollector;
  5. use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
  6. use Drupal\Core\Lock\LockBackendInterface;
  7. /**
  8. * Provides the state system using a key value store.
  9. */
  10. class State extends CacheCollector implements StateInterface {
  11. /**
  12. * The key value store to use.
  13. *
  14. * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
  15. */
  16. protected $keyValueStore;
  17. /**
  18. * Constructs a State object.
  19. *
  20. * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
  21. * The key value store to use.
  22. * @param \Drupal\Core\Cache\CacheBackendInterface $cache
  23. * The cache backend.
  24. * @param \Drupal\Core\Lock\LockBackendInterface $lock
  25. * The lock backend.
  26. */
  27. public function __construct(KeyValueFactoryInterface $key_value_factory, CacheBackendInterface $cache, LockBackendInterface $lock) {
  28. parent::__construct('state', $cache, $lock);
  29. $this->keyValueStore = $key_value_factory->get('state');
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function get($key, $default = NULL) {
  35. $value = parent::get($key);
  36. return $value !== NULL ? $value : $default;
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. protected function resolveCacheMiss($key) {
  42. $value = $this->keyValueStore->get($key);
  43. $this->storage[$key] = $value;
  44. $this->persist($key);
  45. return $value;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function getMultiple(array $keys) {
  51. $values = [];
  52. foreach ($keys as $key) {
  53. $values[$key] = $this->get($key);
  54. }
  55. return $values;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function set($key, $value) {
  61. parent::set($key, $value);
  62. $this->keyValueStore->set($key, $value);
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function setMultiple(array $data) {
  68. foreach ($data as $key => $value) {
  69. parent::set($key, $value);
  70. }
  71. $this->keyValueStore->setMultiple($data);
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function delete($key) {
  77. parent::delete($key);
  78. $this->keyValueStore->delete($key);
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. public function deleteMultiple(array $keys) {
  84. foreach ($keys as $key) {
  85. parent::delete($key);
  86. }
  87. $this->keyValueStore->deleteMultiple($keys);
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function resetCache() {
  93. $this->clear();
  94. }
  95. }