You are here

public function KeyValueStoreExpirable::setWithExpireIfNotExists in MongoDB 8.2

Sets a value for a given key with a time to live if it does not yet exist.

Parameters

string $key: The key of the data to store.

mixed $value: The data to store.

int $expire: The time to live for items, in seconds.

Return value

bool TRUE if the data was set, or FALSE if it already existed.

Overrides KeyValueStoreExpirableInterface::setWithExpireIfNotExists

File

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

Class

KeyValueStoreExpirable
KeyValueStore provides a KeyValueStoreExpirable as a MongoDB collection.

Namespace

Drupal\mongodb_storage

Code

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;
}