You are here

public function NodeViewCountRecordsManager::getNodeViewsCount in Node view count 8

Return count of node views.

Parameters

\Drupal\node\NodeInterface $node: Node object.

\Drupal\user\UserInterface $user: Chosen user for counting or NULL for counting node views of all users.

bool $distinct_users: Should same user node view count as 1 view.

Return value

int Count of node views.

Overrides NodeViewCountRecordsManagerInterface::getNodeViewsCount

File

src/NodeViewCountRecordsManager.php, line 69

Class

NodeViewCountRecordsManager
Provides a class for interacting with nodeviewcount records.

Namespace

Drupal\nodeviewcount

Code

public function getNodeViewsCount(NodeInterface $node, UserInterface $user = NULL, $distinct_users = FALSE) {
  if (!$this
    ->isRecordableForNodeType($node)) {
    return FALSE;
  }
  if (!is_null($user) && !$this
    ->isRecordableForUserRole($user)) {
    return FALSE;
  }
  $query = $this->connection
    ->select('nodeviewcount', 'nvc');
  $query
    ->condition('nid', $node
    ->id(), '=');
  if ($user) {
    $query
      ->condition('uid', $user
      ->id(), '=');
  }
  if ($distinct_users) {
    $query
      ->addExpression('COUNT(DISTINCT uid)');
  }
  else {
    $query
      ->addExpression('COUNT(*)');
  }
  return $query
    ->execute()
    ->fetchAll();
}