You are here

public function FlagService::getFlaggingUsers in Flag 8.4

Get a list of users that have flagged an entity.

$flag = \Drupal::service('flag')
  ->getFlagById('bookmark');
$node = Node::load($node_id);
$flagging_users = \Drupal::service('flag')
  ->getFlaggingUsers($node, $flag);
foreach ($flagging_users as $user) {

  // Do something.
}

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity object.

\Drupal\flag\FlagInterface $flag: (optional) The flag entity to which to restrict results.

Return value

array An array of users who have flagged the entity.

Overrides FlagServiceInterface::getFlaggingUsers

File

src/FlagService.php, line 209

Class

FlagService
Flag service.

Namespace

Drupal\flag

Code

public function getFlaggingUsers(EntityInterface $entity, FlagInterface $flag = NULL) {
  $query = $this->entityTypeManager
    ->getStorage('flagging')
    ->getQuery();
  $query
    ->condition('entity_type', $entity
    ->getEntityTypeId())
    ->condition('entity_id', $entity
    ->id());
  if (!empty($flag)) {
    $query
      ->condition('flag_id', $flag
      ->id());
  }
  $ids = $query
    ->execute();

  // Load the flaggings.
  $flaggings = $this
    ->getFlaggingsByIds($ids);
  $user_ids = [];
  foreach ($flaggings as $flagging) {
    $user_ids[] = $flagging
      ->get('uid')
      ->first()
      ->getValue()['target_id'];
  }
  return $this->entityTypeManager
    ->getStorage('user')
    ->loadMultiple($user_ids);
}