You are here

public function Workspace::delete in Multiversion 8

Deletes an entity permanently.

Throws

\Drupal\Core\Entity\EntityStorageException In case of failures an exception is thrown.

Overrides EntityBase::delete

File

src/Entity/Workspace.php, line 115

Class

Workspace
The workspace entity class.

Namespace

Drupal\multiversion\Entity

Code

public function delete() {
  if (!$this
    ->isNew()) {
    $workspace_id = $this
      ->id();

    // Execute predelete action on workspace entity, this hook is needed to
    // be executed before the workspace is deleted on cron and before entity
    // predelete hooks provided by core.
    \Drupal::moduleHandler()
      ->invokeAll('multiversion_workspace_predelete', [
      $this,
    ]);

    /** @var \Drupal\Core\Queue\QueueInterface $queue */
    $queue = \Drupal::queue('deleted_workspace_queue');
    $queue
      ->createQueue();

    /** @var \Drupal\multiversion\MultiversionManagerInterface $multiversion_manager */
    $multiversion_manager = \Drupal::service('multiversion.manager');
    $entity_type_manager = $this
      ->entityTypeManager();

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity_type */
    foreach ($multiversion_manager
      ->getEnabledEntityTypes() as $entity_type) {

      // Load IDs for deleted entities.
      $deleted_entity_ids = $entity_type_manager
        ->getStorage($entity_type
        ->id())
        ->getQuery()
        ->useWorkspace($workspace_id)
        ->isDeleted()
        ->execute();

      // Load IDs for non-deleted entities.
      $entity_ids = $entity_type_manager
        ->getStorage($entity_type
        ->id())
        ->getQuery()
        ->useWorkspace($workspace_id)
        ->isNotDeleted()
        ->execute();
      foreach (array_merge($entity_ids, $deleted_entity_ids) as $entity_id) {
        $data = [
          'workspace_id' => $workspace_id,
          'entity_type_id' => $entity_type
            ->id(),
          'entity_id' => $entity_id,
        ];
        $queue
          ->createItem($data);
      }
    }

    // Add the workspace to the queue to be deleted.
    $data = [
      'entity_type_id' => 'workspace',
      'entity_id' => $workspace_id,
    ];
    $queue
      ->createItem($data);
    $this
      ->setQueuedForDelete()
      ->save();
    if ($this
      ->id() === $multiversion_manager
      ->getActiveWorkspaceId()) {
      $multiversion_manager
        ->setActiveWorkspaceId(\Drupal::getContainer()
        ->getParameter('workspace.default'));
    }

    // Deleted workspace won't be active anymore for users that had it as
    // active, the default workspace will became active for them.
    $this
      ->deleteWorkspaceActiveSessions($workspace_id);
  }
}