You are here

function comment_entity_predelete in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/comment/comment.module \comment_entity_predelete()

Implements hook_entity_predelete().

File

core/modules/comment/comment.module, line 400
Enables users to comment on published content.

Code

function comment_entity_predelete(EntityInterface $entity) {

  // 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');
    $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);
  }
}