You are here

class KeyValueStoreExpirable in MongoDB 8.2

KeyValueStore provides a KeyValueStoreExpirable as a MongoDB collection.

Hierarchy

Expanded class hierarchy of KeyValueStoreExpirable

1 file declares its use of KeyValueStoreExpirable
KeyValueFactoryTest.php in modules/mongodb_storage/tests/src/Kernel/KeyValueFactoryTest.php

File

modules/mongodb_storage/src/KeyValueStoreExpirable.php, line 14

Namespace

Drupal\mongodb_storage
View source
class KeyValueStoreExpirable extends KeyValueStore implements KeyValueStoreExpirableInterface {

  /**
   * The datetime.time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * {@inheritdoc}
   *
   * @see \Drupal\mongodb_storage\KeyValueStoreExpirable::setTimeService()
   */
  public function __construct($collection, $storeCollection) {
    parent::__construct($collection, $storeCollection);
    $this
      ->ensureIndexes();
  }

  /**
   * Deletes all items from the key/value store.
   */
  public function deleteAll() {
    $this->mongoDbCollection
      ->drop();
    $this
      ->ensureIndexes();
  }

  /**
   * Ensure a TTL index for server-side expirations.
   */
  public function ensureIndexes() {
    $name = $this->mongoDbCollection
      ->getCollectionName();
    $indexMissing = TRUE;
    foreach ($this->mongoDbCollection
      ->listIndexes() as $index) {
      if ($index
        ->isTtl()) {
        $indexMissing = FALSE;
        break;
      }
    }
    if ($indexMissing) {
      $indexes = [
        [
          'expireAfterSeconds' => 0,
          'key' => [
            'expire' => 1,
          ],
          'name' => "ttl_" . $name,
        ],
      ];
      $this->mongoDbCollection
        ->createIndexes($indexes);
    }
  }

  /**
   * Convert a UNIX timestamp to a BSON one for document insertion.
   *
   * @param int $expire
   *   The source timestamp.
   *
   * @return \MongoDB\BSON\UTCDateTime
   *   Its ready-to-insert counterpart.
   */
  protected function getBsonExpire(int $expire) : UTCDateTime {
    return new UTCDateTime(1000 * ($this->time
      ->getCurrentTime() + $expire));
  }

  /**
   * Saves an array of values with a time to live.
   *
   * @param array $data
   *   An array of data to store.
   * @param int $expire
   *   The time to live for items, in seconds.
   */
  public function setMultipleWithExpire(array $data, $expire) {
    foreach ($data as $key => $value) {
      $this
        ->setWithExpire($key, $value, $expire);
    }
  }

  /**
   * Inject the time service. Cannot do it in the constructor for compatibility.
   *
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The datetime.time service.
   */
  public function setTimeService(TimeInterface $time) {
    $this->time = $time;
  }

  /**
   * Saves a value for a given key with a time to live.
   *
   * This does not need microsecond precision, since expires happen with only a
   * multi-second accuracy at best.
   *
   * @param string $key
   *   The key of the data to store.
   * @param mixed $value
   *   The data to store.
   * @param int $expire
   *   The time to live for items, in seconds.
   */
  public function setWithExpire($key, $value, $expire) {
    $selector = [
      '_id' => $this
        ->stringifyKey($key),
    ];
    $replacement = $selector + [
      'expire' => $this
        ->getBsonExpire($expire),
      'value' => serialize($value),
    ];
    $options = [
      'upsert' => TRUE,
    ];
    $this->mongoDbCollection
      ->replaceOne($selector, $replacement, $options);
  }

  /**
   * Sets a value for a given key with a time to live if it does not yet exist.
   *
   * @param string $key
   *   The key of the data to store.
   * @param mixed $value
   *   The data to store.
   * @param int $expire
   *   The time to live for items, in seconds.
   *
   * @return bool
   *   TRUE if the data was set, or FALSE if it already existed.
   */
  public function setWithExpireIfNotExists($key, $value, $expire) {
    $selector = [
      '_id' => $this
        ->stringifyKey($key),
    ];
    $replacement = $selector + [
      'expire' => $this
        ->getBsonExpire($expire),
      'value' => serialize($value),
    ];
    $options = [
      'upsert' => FALSE,
    ];
    $updateResult = $this->mongoDbCollection
      ->replaceOne($selector, $replacement, $options);
    $result = $updateResult
      ->getModifiedCount() ? TRUE : FALSE;
    return $result;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
KeyValueStore::$collectionName protected property The MongoDB collection name, like "kv[ep]_foo" for KV collection "foo".
KeyValueStore::$mongoDbCollection protected property The collection making up the store.
KeyValueStore::deleteMultiple public function Deletes multiple items from the key/value store. Overrides KeyValueStoreInterface::deleteMultiple
KeyValueStore::getAll public function Returns all stored key/value pairs in the collection. Overrides KeyValueStoreInterface::getAll
KeyValueStore::getMultiple public function Returns the stored key/value pairs for a given set of keys. Overrides KeyValueStoreInterface::getMultiple
KeyValueStore::has public function Returns whether a given key exists in the store. Overrides KeyValueStoreInterface::has
KeyValueStore::LEGACY_TYPE_MAP constant
KeyValueStore::PROJECTION_ID constant
KeyValueStore::rename public function Renames a key. Overrides KeyValueStoreInterface::rename
KeyValueStore::set public function Saves a value for a given key. Overrides KeyValueStoreInterface::set
KeyValueStore::setIfNotExists public function Saves a value for a given key if it does not exist yet. Overrides KeyValueStoreInterface::setIfNotExists
KeyValueStore::stringifyKey protected function Represents any value as a string. May incur data loss.
KeyValueStore::__sleep public function
KeyValueStore::__wakeup public function The __wakeup() method cannot use the container, because its constructor is never invoked, and the container itself must not be serialized.
KeyValueStoreExpirable::$time protected property The datetime.time service.
KeyValueStoreExpirable::deleteAll public function Deletes all items from the key/value store. Overrides KeyValueStore::deleteAll
KeyValueStoreExpirable::ensureIndexes public function Ensure a TTL index for server-side expirations.
KeyValueStoreExpirable::getBsonExpire protected function Convert a UNIX timestamp to a BSON one for document insertion.
KeyValueStoreExpirable::setMultipleWithExpire public function Saves an array of values with a time to live. Overrides KeyValueStoreExpirableInterface::setMultipleWithExpire
KeyValueStoreExpirable::setTimeService public function Inject the time service. Cannot do it in the constructor for compatibility.
KeyValueStoreExpirable::setWithExpire public function Saves a value for a given key with a time to live. Overrides KeyValueStoreExpirableInterface::setWithExpire
KeyValueStoreExpirable::setWithExpireIfNotExists public function Sets a value for a given key with a time to live if it does not yet exist. Overrides KeyValueStoreExpirableInterface::setWithExpireIfNotExists
KeyValueStoreExpirable::__construct public function Overrides KeyValueStore::__construct
StorageBase::$collection protected property The name of the collection holding key and value pairs.
StorageBase::delete public function Deletes an item from the key/value store. Overrides KeyValueStoreInterface::delete 1
StorageBase::get public function Returns the stored value for a given key. Overrides KeyValueStoreInterface::get 1
StorageBase::getCollectionName public function Returns the name of this collection. Overrides KeyValueStoreInterface::getCollectionName
StorageBase::setMultiple public function Saves key/value pairs. Overrides KeyValueStoreInterface::setMultiple 1