You are here

function comment_node_search_result in Drupal 8

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

Implements hook_node_search_result().

Formats a comment count string and returns it, for display with search results.

File

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

Code

function comment_node_search_result(EntityInterface $node) {
  $comment_fields = \Drupal::service('comment.manager')
    ->getFields('node');
  $comments = 0;
  $open = FALSE;
  foreach ($comment_fields as $field_name => $info) {

    // Skip fields that entity does not have.
    if (!$node
      ->hasField($field_name)) {
      continue;
    }

    // Do not make a string if comments are hidden.
    $status = $node
      ->get($field_name)->status;
    if (\Drupal::currentUser()
      ->hasPermission('access comments') && $status != CommentItemInterface::HIDDEN) {
      if ($status == CommentItemInterface::OPEN) {

        // At least one comment field is open.
        $open = TRUE;
      }
      $comments += $node
        ->get($field_name)->comment_count;
    }
  }

  // Do not make a string if there are no comment fields, or no comments exist
  // or all comment fields are hidden.
  if ($comments > 0 || $open) {
    return [
      'comment' => \Drupal::translation()
        ->formatPlural($comments, '1 comment', '@count comments'),
    ];
  }
}