You are here

public function WorkspaceManager::purgeDeletedWorkspacesBatch in Workspace 8.2

File

src/WorkspaceManager.php, line 210

Class

WorkspaceManager
Provides the workspace manager.

Namespace

Drupal\workspace

Code

public function purgeDeletedWorkspacesBatch() {
  $deleted_workspace_ids = $this->state
    ->get('workspace.deleted', []);

  // Bail out early if there are no workspaces to purge.
  if (empty($deleted_workspace_ids)) {
    return;
  }
  $batch_size = Settings::get('entity_update_batch_size', 50);

  /** @var \Drupal\workspace\WorkspaceAssociationStorageInterface $workspace_association_storage */
  $workspace_association_storage = $this->entityTypeManager
    ->getStorage('workspace_association');

  // Get the first deleted workspace from the list and delete the revisions
  // associated with it, along with the workspace_association entries.
  $workspace_id = reset($deleted_workspace_ids);
  $workspace_association_ids = $this
    ->getWorkspaceAssociationRevisionsToPurge($workspace_id, $batch_size);
  if ($workspace_association_ids) {
    $workspace_associations = $workspace_association_storage
      ->loadMultipleRevisions(array_keys($workspace_association_ids));
    foreach ($workspace_associations as $workspace_association) {
      $associated_entity_storage = $this->entityTypeManager
        ->getStorage($workspace_association->target_entity_type_id->value);

      // Delete the associated entity revision.
      if ($entity = $associated_entity_storage
        ->loadRevision($workspace_association->target_entity_revision_id->value)) {
        if ($entity
          ->isDefaultRevision()) {
          $entity
            ->delete();
        }
        else {
          $associated_entity_storage
            ->deleteRevision($workspace_association->target_entity_revision_id->value);
        }
      }

      // Delete the workspace_association revision.
      if ($workspace_association
        ->isDefaultRevision()) {
        $workspace_association
          ->delete();
      }
      else {
        $workspace_association_storage
          ->deleteRevision($workspace_association
          ->getRevisionId());
      }
    }
  }

  // The purging operation above might have taken a long time, so we need to
  // request a fresh list of workspace association IDs. If it is empty, we can
  // go ahead and remove the deleted workspace ID entry from state.
  if (!$this
    ->getWorkspaceAssociationRevisionsToPurge($workspace_id, $batch_size)) {
    unset($deleted_workspace_ids[$workspace_id]);
    $this->state
      ->set('workspace.deleted', $deleted_workspace_ids);
  }
}