You are here

public function FlagCountManager::getUserFlagFlaggingCount in Flag 8.4

Gets the count of the flaggings made by a user with a flag.

For example, with a 'bookmarks' flag, this returns the number of bookmarks a user has created.

Parameters

\Drupal\flag\FlagInterface $flag: The flag.

\Drupal\Core\Session\AccountInterface $user: The account.

string $session_id: (optional) The session ID used to specify a unique anonymous user.

Return value

int The number of flaggings for the given flag and user.

Throws

\LogicException Throws an exception if $account is the anonymous user but $session_id is NULL.

Overrides FlagCountManagerInterface::getUserFlagFlaggingCount

File

src/FlagCountManager.php, line 141

Class

FlagCountManager
Class FlagCountManager.

Namespace

Drupal\flag

Code

public function getUserFlagFlaggingCount(FlagInterface $flag, AccountInterface $user, $session_id = NULL) {
  $flag_id = $flag
    ->id();
  $uid = $user
    ->id();
  $get_by_session_id = $user
    ->isAnonymous();

  // Return the flag count if it is already in the cache.
  if ($get_by_session_id) {
    if (is_null($session_id)) {
      throw new \LogicException('Anonymous users must be identified by session_id');
    }

    // Return the flag count if it is already in the cache.
    if (isset($this->userFlagCounts[$flag_id][$uid][$session_id])) {
      return $this->userFlagCounts[$flag_id][$uid][$session_id];
    }
  }
  elseif (isset($this->userFlagCounts[$flag_id][$uid])) {
    return $this->userFlagCounts[$flag_id][$uid];
  }

  // Run the query.
  $query = $this->connection
    ->select('flagging', 'f')
    ->condition('flag_id', $flag_id)
    ->condition('uid', $uid);
  if ($get_by_session_id) {
    $query
      ->condition('session_id', $session_id);
  }
  $query
    ->addExpression('COUNT(*)');
  $result = $query
    ->execute()
    ->fetchField();

  // Cache the result.
  if ($get_by_session_id) {

    // Cached by flag, by uid and by session_id.
    $this->userFlagCounts[$flag_id][$uid][$session_id] = $result;
  }
  else {

    // Cached by flag, by uid.
    $this->userFlagCounts[$flag_id][$uid] = $result;
  }
  return $result;
}