function CommentHooks::entityPredelete

Implements hook_entity_predelete().

Attributes

#[Hook('entity_predelete')]

File

core/modules/comment/src/Hook/CommentHooks.php, line 283

Class

CommentHooks
Hook implementations for comment.

Namespace

Drupal\comment\Hook

Code

public function entityPredelete(EntityInterface $entity) : void {
  // Entities can have non-numeric IDs, but {comment} and
  // {comment_entity_statistics} tables have integer columns for entity ID,
  // and PostgreSQL throws exceptions if you attempt query conditions with
  // mismatched types. So, we need to verify that the ID is numeric (even for
  // an entity type that has an integer ID, $entity->id() might be a string
  // containing a number), and then cast it to an integer when querying.
  if ($entity instanceof FieldableEntityInterface && is_numeric($entity->id())) {
    $entity_query = \Drupal::entityQuery('comment')->accessCheck(FALSE);
    $entity_query->condition('entity_id', (int) $entity->id());
    $entity_query->condition('entity_type', $entity->getEntityTypeId());
    $cids = $entity_query->execute();
    $comment_storage = \Drupal::entityTypeManager()->getStorage('comment');
    $comments = $comment_storage->loadMultiple($cids);
    $comment_storage->delete($comments);
    \Drupal::service('comment.statistics')->delete($entity);
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.