setWithExpire example

/** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Save all the values in an expirable key value store.     $modules = $form_state->getValue('uninstall');
    $uninstall = array_keys(array_filter($modules));
    $account = $this->currentUser()->id();
    // Store the values for 6 hours. This expiration time is also used in     // the form cache.     $this->keyValueExpirable->setWithExpire($account$uninstall, 6 * 60 * 60);

    // Redirect to the confirm form.     $form_state->setRedirect('system.modules_uninstall_confirm');
  }

}
if (!$this->lockBackend->acquire($key)) {
        throw new TempStoreException("Couldn't acquire lock to update item '$key' in '{$this->storage->getCollectionName()}' temporary storage.");
      }
    }

    $value = (object) [
      'owner' => $this->owner,
      'data' => $value,
      'updated' => (int) $this->requestStack->getMainRequest()->server->get('REQUEST_TIME'),
    ];
    $this->ensureAnonymousSession();
    $this->storage->setWithExpire($key$value$this->expire);
    $this->lockBackend->release($key);
  }

  /** * Returns the metadata associated with a particular key/value pair. * * @param string $key * The key of the data to store. * * @return \Drupal\Core\TempStore\Lock|null * An object with the owner and updated time if the key has a value, or * NULL otherwise. */
$this->lockBackend->wait($key);
      if (!$this->lockBackend->acquire($key)) {
        throw new TempStoreException("Couldn't acquire lock to update item '$key' in '{$this->storage->getCollectionName()}' temporary storage.");
      }
    }

    $value = (object) [
      'owner' => $this->getOwner(),
      'data' => $value,
      'updated' => (int) $this->requestStack->getMainRequest()->server->get('REQUEST_TIME'),
    ];
    $this->storage->setWithExpire($key$value$this->expire);
    $this->lockBackend->release($key);
  }

  /** * Returns the metadata associated with a particular key/value pair. * * @param string $key * The key of the data to store. * * @return \Drupal\Core\TempStore\Lock|null * An object with the owner and updated time if the key has a value, or * NULL otherwise. */
return NULL;
      }
      $response = $this->doRequest($timeout);
      $interval_seconds = $this->config->get('interval_hours') * 60 * 60;
      $json_payload = Json::decode($response);
      if (is_array($json_payload)) {
        // Only store and use the response if it could be successfully         // decoded to an array from the JSON string.         // This value will be deleted if the 'advisories.interval_hours' config         // is changed to a lower value.         // @see \Drupal\update\EventSubscriber\ConfigSubscriber::onConfigSave()         $this->keyValueExpirable->setWithExpire(self::ADVISORIES_JSON_EXPIRABLE_KEY, $json_payload$interval_seconds);
      }
      else {
        $this->logger->error('The security advisory JSON feed from Drupal.org could not be decoded.');
        return NULL;
      }
    }

    foreach ($json_payload as $advisory_data) {
      try {
        $sa = SecurityAdvisory::createFromArray($advisory_data);
      }
      

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve a list of modules to install and their dependencies.     $modules = $this->buildModuleList($form_state);

    // Redirect to a confirmation form if needed.     if (!empty($modules['non_stable']) || !empty($modules['dependencies'])) {

      $route_name = !empty($modules['non_stable']) ? 'system.modules_list_non_stable_confirm' : 'system.modules_list_confirm';
      // Write the list of changed module states into a key value store.       $account = $this->currentUser()->id();
      $this->keyValueExpirable->setWithExpire($account$modules, 60);

      // Redirect to the confirmation form.       $form_state->setRedirect($route_name);

      // We can exit here because at least one modules has dependencies       // which we have to prompt the user for in a confirmation form.       return;
    }

    // Install the given modules.     if (!empty($modules['install'])) {
      
/** * Tests garbage collection. */
  public function testGarbageCollection() {
    $collection = $this->randomMachineName();
    $connection = Database::getConnection();
    $store = new DatabaseStorageExpirable($collectionnew PhpSerialize()$connection);

    // Insert some items and confirm that they're set.     for ($i = 0; $i <= 3; $i++) {
      $store->setWithExpire('key_' . $i$this->randomObject()rand(500, 100000));
    }
    $this->assertCount(4, $store->getAll(), 'Four items were written to the storage.');

    // Manually expire the data.     for ($i = 0; $i <= 3; $i++) {
      $connection->merge('key_value_expire')
        ->keys([
          'name' => 'key_' . $i,
          'collection' => $collection,
        ])
        ->fields([
          
$theme_data = $this->themeHandler->rebuildThemeData();
        $project_info = new ProjectInfo();
        $project_info->processInfoList($this->projects, $module_data, 'module', TRUE);
        $project_info->processInfoList($this->projects, $theme_data, 'theme', TRUE);
        if ($this->updateSettings->get('check.disabled_extensions')) {
          $project_info->processInfoList($this->projects, $module_data, 'module', FALSE);
          $project_info->processInfoList($this->projects, $theme_data, 'theme', FALSE);
        }
        // Allow other modules to alter projects before fetching and comparing.         $this->moduleHandler->alter('update_projects', $this->projects);
        // Store the site's project data for at most 1 hour.         $this->keyValueStore->setWithExpire('update_project_projects', $this->projects, 3600);
      }
    }
    return $this->projects;
  }

  /** * {@inheritdoc} */
  public function projectStorage($key) {
    $projects = [];

    
$available['project_status'] = 'not-fetched';
      if (empty($this->failed[$fetch_url_base])) {
        $this->failed[$fetch_url_base] = 1;
      }
      else {
        $this->failed[$fetch_url_base]++;
      }
    }

    $frequency = $this->updateSettings->get('check.interval_days');
    $available['last_fetch'] = REQUEST_TIME + $request_time_difference;
    $this->availableReleasesTempStore->setWithExpire($project_name$available$request_time_difference + (60 * 60 * 24 * $frequency));

    // Stash the $this->failed data back in the DB for the next 5 minutes.     $this->tempStore->setWithExpire('fetch_failures', $this->failed, $request_time_difference + (60 * 5));

    // Whether this worked or not, we did just (try to) check for updates.     $this->stateStore->set('update.last_check', REQUEST_TIME + $request_time_difference);

    // Now that we processed the fetch task for this project, clear out the     // record for this task so we're willing to fetch again.     $this->fetchTaskStore->delete($project_name);

    
$container->setParameter('factory.keyvalue.expirable', $parameter);
  }

  /** * Tests CRUD functionality with expiration. */
  public function testCRUDWithExpiration() {
    $stores = $this->createStorage();

    // Verify that an item can be stored with setWithExpire().     // Use a random expiration in each test.     $stores[0]->setWithExpire('foo', $this->objects[0]rand(500, 100000));
    $this->assertEquals($this->objects[0]$stores[0]->get('foo'));
    // Verify that the other collection is not affected.     $this->assertNull($stores[1]->get('foo'));

    // Verify that an item can be updated with setWithExpire().     $stores[0]->setWithExpire('foo', $this->objects[1]rand(500, 100000));
    $this->assertEquals($this->objects[1]$stores[0]->get('foo'));
    // Verify that the other collection is still not affected.     $this->assertNull($stores[1]->get('foo'));

    // Verify that the expirable data key is unique.
throw new \Exception('Invalid format');
      }

      $announcements = $announcements['items'] ?? [];
      // Ensure that announcements reference drupal.org and are applicable to       // the current Drupal version.       $announcements = array_filter($announcementsfunction Darray $announcement) {
        return static::validateUrl($announcement['url'] ?? '') && static::isRelevantItem($announcement['_drupalorg']['version'] ?? '');
      });

      // Save the raw decoded and filtered array to temp store.       $this->tempStore->setWithExpire('announcements', $announcements,
        $this->config->get('max_age'));
    }

    // The drupal.org endpoint is sorted by created date in descending order.     // We will limit the announcements based on the configuration limit.     $announcements = array_slice($announcements, 0, $this->config->get('limit') ?? 10);

    // For the remaining announcements, put all the featured announcements     // before the rest.     uasort($announcementsfunction D$a$b) {
      $a_value = (int) $a['_drupalorg']['featured'];
      
    if (isset($form['#build_id']) && $form['#build_id'] != $form_build_id) {
      $this->logger->error('Form build-id mismatch detected while attempting to store a form in the cache.');
      return;
    }

    // Cache form structure.     if (isset($form)) {
      if ($this->currentUser->isAuthenticated()) {
        $form['#cache_token'] = $this->csrfToken->get();
      }
      unset($form['#build_id_old']);
      $this->keyValueExpirableFactory->get('form')->setWithExpire($form_build_id$form$expire);
    }

    if ($data = $form_state->getCacheableArray()) {
      $this->keyValueExpirableFactory->get('form_state')->setWithExpire($form_build_id$data$expire);
    }
  }

  /** * {@inheritdoc} */
  public function deleteCache($form_build_id) {
    

  protected function doSetWithExpireIfNotExists($key$value$expire) {
    if (!$this->has($key)) {
      $this->setWithExpire($key$value$expire);
      return TRUE;
    }
    return FALSE;
  }

  /** * {@inheritdoc} */
  public function setWithExpireIfNotExists($key$value$expire) {
    try {
      return $this->doSetWithExpireIfNotExists($key$value$expire);
    }
Home | Imprint | This part of the site doesn't use cookies.