You are here

protected function OgContext::getBestCandidate in Organic groups 8

Returns information about the group which best matches the current context.

Return value

array|null An associative array with information about the chosen candidate. It has the following keys:

  • entity: the group entity.
  • votes: an array of votes that have been cast for this entity.
  • cache_contexts: an array of cache contexts that were used to discover this group.

If no group was found in the current context, NULL is returned.

See also

\Drupal\og\OgGroupResolverInterface

1 call to OgContext::getBestCandidate()
OgContext::getOgContext in src/ContextProvider/OgContext.php
Returns the context object containing the relevant group.

File

src/ContextProvider/OgContext.php, line 129

Class

OgContext
Provides the group that best matches the current context.

Namespace

Drupal\og\ContextProvider

Code

protected function getBestCandidate() {
  $collection = new OgResolvedGroupCollection();

  // Retrieve the list of group resolvers. These are stored in config, and are
  // ordered by priority.
  $group_resolvers = $this->configFactory
    ->get('og.settings')
    ->get('group_resolvers');
  $priority = 0;
  foreach ($group_resolvers as $plugin_id) {

    /** @var \Drupal\og\OgGroupResolverInterface $plugin */
    if ($plugin = $this->pluginManager
      ->createInstance($plugin_id)) {

      // Set the default vote weight according to the plugin's priority.
      $collection
        ->setVoteWeight($priority);

      // Let the plugin do its magic.
      $plugin
        ->resolve($collection);

      // If the plugin is certain that the candidate belongs to the current
      // context, it can declare the search to be over.
      if ($plugin
        ->isPropagationStopped()) {
        break;
      }

      // The next plugin we try will have a lower priority.
      $priority--;
    }
  }

  // Sort the resolved groups and retrieve the first result, this will be the
  // best candidate.
  $collection
    ->sort();
  $group_info = $collection
    ->getGroupInfo();
  if (!empty($group_info)) {
    return reset($group_info);
  }
  return NULL;
}