You are here

public function FileLinkClassFormatter::viewElements in Element Class Formatter 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/FileLinkClassFormatter.php, line 79

Class

FileLinkClassFormatter
Plugin implementation of the 'file link with class' formatter.

Namespace

Drupal\element_class_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $class = $this
    ->getSetting('class');
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $file) {
    $item = $file->_referringItem;

    // Get default link text.
    $link_text = $this
      ->getSetting('use_description_as_link_text') ? $item->description : $item
      ->getEntity()
      ->label();
    $attributes = new Attribute();
    $attributes
      ->setAttribute('title', $file
      ->getFilename());

    // File meta data.
    $file_type = strtoupper(pathinfo($file
      ->getFilename(), PATHINFO_EXTENSION));
    $file_size = format_size($file
      ->getSize());
    $mime_type = $file
      ->getMimeType();
    $attributes
      ->setAttribute('type', $mime_type . '; length=' . $file
      ->getSize());

    // Classes for styling.
    $classes = [
      'file',
      'file--mime-' . strtr($mime_type, [
        '/' => '-',
        '.' => '-',
      ]),
      'file--' . file_icon_class($mime_type),
      $class,
    ];
    $attributes
      ->addClass($classes);

    // Customise link text.
    $show_filesize = $this
      ->getSetting('show_filesize');
    $show_filetype = $this
      ->getSetting('show_filetype');
    if ($show_filesize && $show_filetype) {
      $link_text = $link_text . ' (' . $file_type . ', ' . $file_size . ')';
    }
    elseif ($show_filesize && !$show_filetype) {
      $link_text = $link_text . ' (' . $file_size . ')';
    }
    elseif (!$show_filesize && $show_filetype) {
      $link_text = $link_text . ' (' . $file_type . ')';
    }
    $elements[$delta] = [
      '#type' => 'link',
      '#title' => $link_text,
      '#url' => Url::fromUri($file
        ->createFileUrl(FALSE)),
      '#attributes' => $attributes
        ->toArray(),
      '#cache' => [
        'tags' => $file
          ->getCacheTags(),
      ],
    ];
  }
  return $elements;
}