You are here

public function CommentStorage::getDisplayOrdinal in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/comment/src/CommentStorage.php \Drupal\comment\CommentStorage::getDisplayOrdinal()

Gets the display ordinal or page number for a comment.

Parameters

\Drupal\comment\CommentInterface $comment: The comment to use as a reference point.

int $comment_mode: The comment display mode: CommentManagerInterface::COMMENT_MODE_FLAT or CommentManagerInterface::COMMENT_MODE_THREADED.

int $divisor: Defaults to 1, which returns the display ordinal for a comment. If the number of comments per page is provided, the returned value will be the page number. (The return value will be divided by $divisor.)

Return value

int The display ordinal or page number for the comment. It is 0-based, so will represent the number of items before the given comment/page.

Overrides CommentStorageInterface::getDisplayOrdinal

File

core/modules/comment/src/CommentStorage.php, line 110

Class

CommentStorage
Defines the storage handler class for comments.

Namespace

Drupal\comment

Code

public function getDisplayOrdinal(CommentInterface $comment, $comment_mode, $divisor = 1) {

  // Count how many comments (c1) are before $comment (c2) in display order.
  // This is the 0-based display ordinal.
  $data_table = $this
    ->getDataTable();
  $query = $this->database
    ->select($data_table, 'c1');
  $query
    ->innerJoin($data_table, 'c2', 'c2.entity_id = c1.entity_id AND c2.entity_type = c1.entity_type AND c2.field_name = c1.field_name');
  $query
    ->addExpression('COUNT(*)', 'count');
  $query
    ->condition('c2.cid', $comment
    ->id());
  if (!$this->currentUser
    ->hasPermission('administer comments')) {
    $query
      ->condition('c1.status', CommentInterface::PUBLISHED);
  }
  if ($comment_mode == CommentManagerInterface::COMMENT_MODE_FLAT) {

    // For rendering flat comments, cid is used for ordering comments due to
    // unpredictable behavior with timestamp, so we make the same assumption
    // here.
    $query
      ->condition('c1.cid', $comment
      ->id(), '<');
  }
  else {

    // For threaded comments, the c.thread column is used for ordering. We can
    // use the sorting code for comparison, but must remove the trailing
    // slash.
    $query
      ->where('SUBSTRING(c1.thread, 1, (LENGTH(c1.thread) - 1)) < SUBSTRING(c2.thread, 1, (LENGTH(c2.thread) - 1))');
  }
  $query
    ->condition('c1.default_langcode', 1);
  $query
    ->condition('c2.default_langcode', 1);
  $ordinal = $query
    ->execute()
    ->fetchField();
  return $divisor > 1 ? floor($ordinal / $divisor) : $ordinal;
}