createItem example


class ComputedReferenceTestFieldItemList extends EntityReferenceFieldItemList {

  use ComputedItemListTrait;

  /** * Compute the list property from state. */
  protected function computeValue() {
    foreach (\Drupal::state()->get('entity_test_reference_computed_target_ids', []) as $delta => $id) {
      $this->list[$delta] = $this->createItem($delta$id);
    }
  }

}
$path_alias_repository = \Drupal::service('path_alias.repository');

      if ($path_alias = $path_alias_repository->lookupBySystemPath('/' . $entity->toUrl()->getInternalPath()$this->getLangcode())) {
        $value = [
          'alias' => $path_alias['alias'],
          'pid' => $path_alias['id'],
          'langcode' => $path_alias['langcode'],
        ];
      }
    }

    $this->list[0] = $this->createItem(0, $value);
  }

  /** * {@inheritdoc} */
  public function defaultAccess($operation = 'view', AccountInterface $account = NULL) {
    if ($operation == 'view') {
      return AccessResult::allowed();
    }
    return AccessResult::allowedIfHasPermissions($account['create url aliases', 'administer url aliases'], 'OR')->cachePerPermissions();
  }

  
/** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    parent::postSave($storage$update);
    $is_new = !$update;
    foreach ($this->translations as $langcode => $data) {
      if ($this->hasTranslation($langcode)) {
        $translation = $this->getTranslation($langcode);
        if ($translation->bundle->entity->thumbnailDownloadsAreQueued() && $translation->shouldUpdateThumbnail($is_new)) {
          \Drupal::queue('media_entity_thumbnail')->createItem(['id' => $translation->id()]);
        }
      }
    }
  }

  /** * {@inheritdoc} */
  public function preSaveRevision(EntityStorageInterface $storage, \stdClass $record) {
    parent::preSaveRevision($storage$record);

    
unset($args[$last]);
    }
    $args = array_merge($args[&$batch_context]);

    // Call the batch operation function.     call_user_func_array($function$args);

    // If the batch operation is not finished we create a new queue task to     // continue the task. This is typically the translation import task.     if ($batch_context['finished'] < 1) {
      unset($batch_context['strings']);
      $this->queue->createItem([$function$args]);
    }
  }

}

    else {
      // Only arrays with numeric keys are supported.       if (!is_array($values)) {
        throw new \InvalidArgumentException('Cannot set a list with a non-array value.');
      }
      // Assign incoming values. Keys are renumbered to ensure 0-based       // sequential deltas. If possible, reuse existing items rather than       // creating new ones.       foreach (array_values($values) as $delta => $value) {
        if (!isset($this->list[$delta])) {
          $this->list[$delta] = $this->createItem($delta$value);
        }
        else {
          $this->list[$delta]->setValue($value, FALSE);
        }
      }
      // Truncate extraneous pre-existing values.       $this->list = array_slice($this->list, 0, count($values));
    }
    // Notify the parent of any changes.     if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
/** * {@inheritdoc} */
  protected function computeValue() {
    $moderation_state = $this->getModerationStateId();
    // Do not store NULL values, in the case where an entity does not have a     // moderation workflow associated with it, we do not create list items for     // the computed field.     if ($moderation_state) {
      // An entity can only have a single moderation state.       $this->list[0] = $this->createItem(0, $moderation_state);
    }
  }

  /** * Gets the moderation state ID linked to a content entity revision. * * @return string|null * The moderation state ID linked to a content entity revision. */
  protected function getModerationStateId() {
    $entity = $this->getEntity();

    
/** * Compute the list property from state. */
  protected function computeValue() {
    // Count the number of times this method has been executed during the     // lifecycle of an entity.     $execution_count = \Drupal::state()->get('computed_test_field_execution', 0);
    \Drupal::state()->set('computed_test_field_execution', ++$execution_count);

    foreach (\Drupal::state()->get('entity_test_computed_field_item_list_value', []) as $delta => $item) {
      $this->list[$delta] = $this->createItem($delta$item);
    }
  }

}

  }

  /** * Tests the ::processQueues() method. * * @covers ::processQueues * @dataProvider processQueuesTestData */
  public function testProcessQueues($item$message_logged_assertion$count_post_run) {
    $this->resetTestingState();
    $this->queue->createItem($item);
    $this->assertFalse($this->state->get('cron_test.message_logged'));
    $this->assertEquals(1, $this->queue->numberOfItems());
    $this->cron->run();
    $this->{$message_logged_assertion}($this->state->get('cron_test.message_logged'));
    $this->assertEquals($count_post_run$this->queue->numberOfItems());
  }

  /** * Verify that RequeueException causes an item to be processed multiple times. */
  public function testRequeueException() {
    
// Ensure that the queues are of the correct type for this test.     $this->assertInstanceOf('Drupal\Core\Queue\DelayableQueueInterface', $database);
    $this->assertNotInstanceOf('Drupal\Core\Queue\DelayableQueueInterface', $memory);

    // Get the queue worker plugin manager.     $manager = $this->container->get('plugin.manager.queue_worker');
    $definitions = $manager->getDefinitions();
    $this->assertNotEmpty($database_lease_time = $definitions['cron_queue_test_database_delay_exception']['cron']['time']);
    $this->assertNotEmpty($memory_lease_time = $definitions['cron_queue_test_memory_delay_exception']['cron']['time']);

    // Create the necessary test data and run cron.     $database->createItem('test');
    $memory->createItem('test');
    $this->cron->run();

    // Fetch the expiry time for the database queue.     $query = $this->connection->select('queue');
    $query->condition('name', 'cron_queue_test_database_delay_exception');
    $query->addField('queue', 'expire');
    $query->range(0, 1);
    $expire = $query->execute()->fetchField();

    // Assert that the delay interval is greater than the lease interval. This

  protected function runQueueTest($queue1$queue2) {
    // Create four items.     $data = [];
    for ($i = 0; $i < 4; $i++) {
      $data[] = [$this->randomMachineName() => $this->randomMachineName()];
    }

    // Queue items 1 and 2 in the queue1.     $queue1->createItem($data[0]);
    $queue1->createItem($data[1]);

    // Retrieve two items from queue1.     $items = [];
    $new_items = [];

    $items[] = $item = $queue1->claimItem();
    $new_items[] = $item->data;

    $items[] = $item = $queue1->claimItem();
    $new_items[] = $item->data;

    

class ComputedTestCacheableStringItemList extends FieldItemList {

  use ComputedItemListTrait;

  /** * {@inheritdoc} */
  protected function computeValue() {
    /** @var \Drupal\entity_test\Plugin\Field\FieldType\ComputedTestCacheableStringItem $item */
    $item = $this->createItem(0, 'computed test cacheable string field');
    $cacheability = (new CacheableMetadata())
      ->setCacheContexts(['url.query_args:computed_test_cacheable_string_field'])
      ->setCacheTags(['field:computed_test_cacheable_string_field'])
      ->setCacheMaxAge(800);
    $item->get('value')->addCacheableDependency($cacheability);
    $this->list[0] = $item;
  }

}
$request_time = \Drupal::time()->getRequestTime();
  \Drupal::database()->delete('mymodule_table')
    ->condition('expires', $expires, '>=')
    ->execute();
  \Drupal::state()->set('mymodule.last_check', $request_time);

  // Long-running operation example, leveraging a queue:   // Queue news feeds for updates once their refresh interval has elapsed.   $queue = \Drupal::queue('mymodule.feeds');
  $ids = \Drupal::entityTypeManager()->getStorage('mymodule_feed')->getFeedIdsToRefresh();
  foreach (Feed::loadMultiple($ids) as $feed) {
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.       $feed->setQueuedTime($request_time);
      $feed->save();
    }
  }
  $ids = \Drupal::entityQuery('mymodule_feed')
    ->accessCheck(FALSE)
    ->condition('queued', $request_time - (3600 * 6), '<')
    ->execute();
  if ($ids) {
    $feeds = Feed::loadMultiple($ids);
    
$this->failed = [];
  }

  /** * {@inheritdoc} */
  public function createFetchTask($project) {
    if (empty($this->fetchTasks)) {
      $this->fetchTasks = $this->fetchTaskStore->getAll();
    }
    if (empty($this->fetchTasks[$project['name']])) {
      $this->fetchQueue->createItem($project);
      $this->fetchTaskStore->set($project['name']$project);
      $this->fetchTasks[$project['name']] = REQUEST_TIME;
    }
  }

  /** * {@inheritdoc} */
  public function fetchData() {
    $end = time() + $this->updateSettings->get('fetch.timeout');
    if ($this->fetchQueue->numberOfItems()) {
      
Home | Imprint | This part of the site doesn't use cookies.