You are here

public function SmartQueue::onQueuePostSave in Entityqueue 8

Acts on an entity queue before the insert or update hook is invoked.

Parameters

\Drupal\entityqueue\EntityQueueInterface $queue: The entity queue object.

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

bool $update: TRUE if the queue has been updated, or FALSE if it has been inserted.

Overrides EntityQueueHandlerBase::onQueuePostSave

File

modules/entityqueue_smartqueue/src/Plugin/EntityQueueHandler/SmartQueue.php, line 188

Class

SmartQueue
Plugin annotation @EntityQueueHandler( id = "smartqueue", title = @Translation("Smart queue"), description = @Translation("Provides automated subqueues for each entity of a given type."), )

Namespace

Drupal\entityqueue_smartqueue\Plugin\EntityQueueHandler

Code

public function onQueuePostSave(EntityQueueInterface $queue, EntityStorageInterface $storage, $update = TRUE) {
  parent::onQueuePostSave($queue, $storage, $update);
  $operations = [];

  // Generate list of subqueues to be deleted, and add batch operations
  // to delete them.
  // 1. Get the existing subqueue ids.
  $subqueue_ids = $this->entityTypeManager
    ->getStorage('entity_subqueue')
    ->getQuery()
    ->condition('queue', $queue
    ->id())
    ->execute();

  // 2. Get the list of relevant subqueues for this queue.
  $subqueue_id_list = array_map(function ($subqueue_id) use ($queue) {
    return $queue
      ->id() . '__' . $subqueue_id;
  }, $this
    ->getEntityIds());

  // 3. Get a diff of both, so we know which subqueues we don't need anymore.
  $subqueue_diff = array_diff($subqueue_ids, $subqueue_id_list);
  $subqueue_diff_chunks = array_chunk($subqueue_diff, 20);
  foreach ($subqueue_diff_chunks as $subqueue_diff_chunk) {
    $operations[] = [
      [
        $this,
        'deleteSubqueues',
      ],
      [
        $subqueue_diff_chunk,
      ],
    ];
  }

  // Generate list of subqueues to be created, and add batch operations to
  // create them.
  $entity_ids = $this
    ->getEntityIds();
  $entity_id_chunks = array_chunk($entity_ids, 20);
  foreach ($entity_id_chunks as $entity_id_chunk) {
    $operations[] = [
      [
        $this,
        'initSubqueuesCreate',
      ],
      [
        $queue,
        $entity_id_chunk,
        $this->configuration['entity_type'],
      ],
    ];
  }
  $batch = [
    'title' => t('Creating/deleting subqueues according to configuration'),
    'operations' => $operations,
    'finished' => [
      get_class($this),
      'initSubqueuesFinished',
    ],
  ];
  batch_set($batch);
}