You are here

public function VotingApiReactionManager::getReactions in Voting API Reaction 8

Return rendered list of active reactions.

Parameters

array $settings: Field settings.

array $results: Array containing Voting API voting results.

Return value

array Rendered reactions.

File

src/VotingApiReactionManager.php, line 208

Class

VotingApiReactionManager
Manages reactions through Voting API entities.

Namespace

Drupal\votingapi_reaction

Code

public function getReactions(array $settings, array $results) {

  // Get only enabled reactions.
  $entities = array_filter($this
    ->allReactions(), function (VoteType $entity) use ($settings) {
    return in_array($entity
      ->id(), array_filter($settings['reactions']));
  });

  // Configure the object.
  $reactions = array_map(function (VoteType $entity) use ($settings, $results) {
    $reaction = [
      '#theme' => 'votingapi_reaction_item',
      '#reaction' => $entity
        ->id(),
    ];
    if ($settings['show_icon']) {
      $reaction['#icon'] = $this
        ->getIcon($entity);
    }
    if ($settings['show_label']) {
      $reaction['#label'] = $entity
        ->label();
    }
    if ($settings['show_count']) {
      $reaction['#count'] = isset($results[$entity
        ->id()]['vote_sum']) ? $results[$entity
        ->id()]['vote_sum'] : 0;
    }
    return $reaction;
  }, $entities);

  // Sorting.
  if ($settings['sort_reactions'] != 'none') {
    uasort($reactions, function ($a, $b) use ($settings, $results) {
      $count_a = isset($results[$a['#reaction']]['vote_count']) ? $results[$a['#reaction']]['vote_count'] : 0;
      $count_b = isset($results[$b['#reaction']]['vote_count']) ? $results[$b['#reaction']]['vote_count'] : 0;
      if ($settings['sort_reactions'] == 'desc') {
        return $count_a > $count_b ? -1 : 1;
      }
      else {
        return $count_a < $count_b ? -1 : 1;
      }
    });
  }

  // Render reactions.
  return array_map(function ($reaction) {
    return $this->renderer
      ->render($reaction);
  }, $reactions);
}