You are here

public function ForumIndexStorage::updateIndex in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/forum/src/ForumIndexStorage.php \Drupal\forum\ForumIndexStorage::updateIndex()
  2. 9 core/modules/forum/src/ForumIndexStorage.php \Drupal\forum\ForumIndexStorage::updateIndex()

File

core/modules/forum/src/ForumIndexStorage.php, line 93

Class

ForumIndexStorage
Handles CRUD operations to {forum_index} table.

Namespace

Drupal\forum

Code

public function updateIndex(NodeInterface $node) {
  $nid = $node
    ->id();
  $count = $this->database
    ->query("SELECT COUNT([cid]) FROM {comment_field_data} [c] INNER JOIN {forum_index} [i] ON [c].[entity_id] = [i].[nid] WHERE [c].[entity_id] = :nid AND [c].[field_name] = 'comment_forum' AND [c].[entity_type] = 'node' AND [c].[status] = :status AND [c].[default_langcode] = 1", [
    ':nid' => $nid,
    ':status' => CommentInterface::PUBLISHED,
  ])
    ->fetchField();
  if ($count > 0) {

    // Comments exist.
    $last_reply = $this->database
      ->queryRange("SELECT [cid], [name], [created], [uid] FROM {comment_field_data} WHERE [entity_id] = :nid AND [field_name] = 'comment_forum' AND [entity_type] = 'node' AND [status] = :status AND [default_langcode] = 1 ORDER BY [cid] DESC", 0, 1, [
      ':nid' => $nid,
      ':status' => CommentInterface::PUBLISHED,
    ])
      ->fetchObject();
    $this->database
      ->update('forum_index')
      ->fields([
      'comment_count' => $count,
      'last_comment_timestamp' => $last_reply->created,
    ])
      ->condition('nid', $nid)
      ->execute();
  }
  else {

    // Comments do not exist.
    // @todo This should be actually filtering on the desired node language
    $this->database
      ->update('forum_index')
      ->fields([
      'comment_count' => 0,
      'last_comment_timestamp' => $node
        ->getCreatedTime(),
    ])
      ->condition('nid', $nid)
      ->execute();
  }
}