You are here

function poll_tokens in Poll 8

Implements hook_tokens().

File

./poll.tokens.inc, line 43
Builds placeholder replacement tokens for values specific to Poll nodes.

Code

function poll_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'poll' && !empty($data['poll'])) {

    /** @var \Drupal\poll\Entity\Poll $poll */
    $poll = $data['poll'];
    $total_votes = 0;
    $highest_votes = 0;
    foreach ($poll
      ->getVotes() as $vote) {
      $total_votes += $vote;
    }
    $options = $poll
      ->getOptions();
    foreach ($poll
      ->getVotes() as $pid => $vote) {
      if ($vote > $highest_votes) {
        $winner = $options[$pid];
        $highest_votes = $vote;
      }
    }
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'votes':
          $replacements[$original] = $total_votes;
          break;
        case 'winner':
          if (isset($winner)) {
            $replacements[$original] = $winner;
          }
          else {
            $replacements[$original] = '';
          }
          break;
        case 'winner-votes':
          if (isset($winner)) {
            $replacements[$original] = $highest_votes;
          }
          else {
            $replacements[$original] = '';
          }
          break;
        case 'winner-percent':
          if (isset($winner)) {
            $percent = $highest_votes / $total_votes * 100;
            $replacements[$original] = number_format($percent, 0);
          }
          else {
            $replacements[$original] = '';
          }
          break;
        case 'duration':
          $replacements[$original] = \Drupal::service('date.formatter')
            ->formatInterval($poll
            ->getRuntime());
          break;
      }
    }
  }
  return $replacements;
}