You are here

public function FlagService::getEntityFlaggings in Flag 8.4

Get flaggings for the given entity, flag, and optionally, user.

This method works very much like FlagServiceInterface::getFlagging() only it returns all flaggings matching the given parameters.

$flag = \Drupal::service('flag')
  ->getFlagById('bookmark');
$node = Node::load($node_id);
$flaggings = \Drupal::service('flag')
  ->getEntityFlaggings($flag, $node);
foreach ($flaggings as $flagging) {

  // Do something with each flagging.
}

Parameters

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

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

\Drupal\Core\Session\AccountInterface $account: (optional) The account of the flagging user. If NULL, flaggings for any user will be returned.

string $session_id: (optional) The session ID. This must be supplied if $account is the anonymous user.

Return value

array An array of flaggings.

Throws

\LogicException An exception is thrown if the given $account is anonymous, but no $session_id is given.

Overrides FlagServiceInterface::getEntityFlaggings

1 call to FlagService::getEntityFlaggings()
FlagService::getFlagging in src/FlagService.php
Get a single flagging for given a flag and entity.

File

src/FlagService.php, line 132

Class

FlagService
Flag service.

Namespace

Drupal\flag

Code

public function getEntityFlaggings(FlagInterface $flag, EntityInterface $entity, AccountInterface $account = NULL, $session_id = NULL) {
  $query = $this->entityTypeManager
    ->getStorage('flagging')
    ->getQuery();
  $query
    ->condition('flag_id', $flag
    ->id());
  if (!is_null($account)) {
    if (!$flag
      ->isGlobal()) {
      $query
        ->condition('uid', $account
        ->id());

      // Add the session ID to the query if $account is the anonymous user
      // (and require the $session_id parameter in this case).
      if ($account
        ->isAnonymous()) {
        if (empty($session_id)) {
          throw new \LogicException('An anonymous user must be identified by session ID.');
        }
        $query
          ->condition('session_id', $session_id);
      }
    }
  }
  $query
    ->condition('entity_type', $entity
    ->getEntityTypeId())
    ->condition('entity_id', $entity
    ->id());
  $ids = $query
    ->execute();
  return $this
    ->getFlaggingsByIds($ids);
}