You are here

function content_lock_entity_predelete in Content locking (anti-concurrent editing) 8

Same name and namespace in other branches
  1. 8.2 content_lock.module \content_lock_entity_predelete()

Implements hook_entity_predelete().

Check if the entity attempting to be deleted is locked and prevent deletion.

File

./content_lock.module, line 171
Content lock - Main functions of the module.

Code

function content_lock_entity_predelete(EntityInterface $entity) {
  $entity_id = $entity
    ->id();
  $entity_type = $entity
    ->getEntityTypeId();

  /** @var \Drupal\content_lock\ContentLock\ContentLock $lock_service */
  $lock_service = \Drupal::service('content_lock');
  if (!$lock_service
    ->isLockable($entity)) {
    return;
  }
  $data = $lock_service
    ->fetchLock($entity_id, NULL, $entity
    ->language()
    ->getId(), $entity_type);
  if ($data !== FALSE) {
    $current_user = \Drupal::currentUser();

    // If the entity is locked, and current user is not the lock's owner,
    // set a message and stop deletion.
    if ($current_user
      ->id() !== $data->uid) {
      $lock_user = User::load($data->uid);
      $message = t('@entity cannot be deleted because it was locked by @user since @time.', [
        '@entity' => $entity
          ->label(),
        '@user' => $lock_user
          ->getDisplayName(),
        '@time' => \Drupal::service('date.formatter')
          ->formatInterval(REQUEST_TIME - $data->timestamp),
      ]);
      \Drupal::messenger()
        ->addWarning($message);
      $url = Url::fromRoute('entity.' . $entity_type . '.canonical', [
        $entity_type => $entity_id,
      ])
        ->toString();
      $redirect = new LocalRedirectResponse($url);
      $redirect
        ->send();
      exit(0);
    }
  }
}