setWithExpireIfNotExists example


  public function setIfNotExists($key$value) {
    $value = (object) [
      'owner' => $this->owner,
      'data' => $value,
      'updated' => (int) $this->requestStack->getMainRequest()->server->get('REQUEST_TIME'),
    ];
    $this->ensureAnonymousSession();
    $set = $this->storage->setWithExpireIfNotExists($key$value$this->expire);
    return $set;
  }

  /** * Stores a particular key/value pair in this SharedTempStore. * * Only stores the given key/value pair if it does not exist yet or is owned * by $this->owner. * * @param string $key * The key of the data to store. * @param mixed $value * The data to store. * * @return bool * TRUE if the data was set, or FALSE if it already exists and is not owned * by $this->user. * * @throws \Drupal\Core\TempStore\TempStoreException * Thrown when a lock for the backend storage could not be acquired. */
$this->assertNull($stores[0]->get('foo'));
    $this->assertNull($stores[0]->get('bar'));
    $this->assertEmpty($stores[0]->getMultiple(['foo', 'bar']));
    // Verify that the item in the other collection still exists.     $this->assertEquals($this->objects[5]$stores[1]->get('foo'));

    // Test that setWithExpireIfNotExists() succeeds only the first time.     $key = $this->randomMachineName();
    for ($i = 0; $i <= 1; $i++) {
      // setWithExpireIfNotExists() should be TRUE the first time (when $i is       // 0) and FALSE the second time (when $i is 1).       $this->assertEquals(!$i$stores[0]->setWithExpireIfNotExists($key$this->objects[$i]rand(500, 100000)));
      $this->assertEquals($this->objects[0]$stores[0]->get($key));
      // Verify that the other collection is not affected.       $this->assertNull($stores[1]->get($key));
    }

    // Remove the item and try to set it again.     $stores[0]->delete($key);
    $stores[0]->setWithExpireIfNotExists($key$this->objects[1]rand(500, 100000));
    // This time it should succeed.     $this->assertEquals($this->objects[1]$stores[0]->get($key));
    // Verify that the other collection is still not affected.
Home | Imprint | This part of the site doesn't use cookies.