You are here

public function RatingFormatter::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/RatingFormatter.php, line 24

Class

RatingFormatter
Plugin implementation of the 'fivestar_rating' 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_rating',
      '#instance_settings' => $item
        ->getFieldDefinition()
        ->getSettings(),
      '#item' => $values,
    ];
  }
  else {
    $elements[] = [
      '#markup' => $this
        ->t('No votes yet'),
    ];
  }
  return $elements;
}