You are here

public function PercentageFormatter::viewElements in Fivestar 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/PercentageFormatter.php, line 24

Class

PercentageFormatter
Plugin implementation of the 'fivestar_percentage' formatter.

Namespace

Drupal\fivestar\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $values = [
    'user' => 0,
    'average' => 0,
    'count' => 0,
  ];
  $rating = [];
  $users = [];
  $elements = [];
  if (!$items
    ->isEmpty()) {

    /** @var \Drupal\fivestar\Plugin\Field\FieldType\FivestarItem $item */
    foreach ($items as $delta => $item) {
      $value = $item
        ->getValue();
      $rating[] = $value['rating'];
      $users[] = $value['target'];
      $values['count'] += 1;
    }
    if (!empty($rating)) {
      $values['average'] = array_sum($rating) / $values['count'];
      $users = array_unique($users);
      $values['user'] = count($users);
    }
    $elements[] = [
      '#theme' => 'fivestar_formatter_percentage',
      '#instance_settings' => $item
        ->getFieldDefinition()
        ->getSettings(),
      '#item' => $values,
    ];
  }
  else {
    $elements[] = [
      '#markup' => $this
        ->t('No votes yet'),
    ];
  }
  return $elements;
}