You are here

public function FileVideoFormatter::viewElements in File Entity (fieldable files) 8.2

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/FileVideoFormatter.php, line 177

Class

FileVideoFormatter
Plugin implementation of the 'file_video' formatter.

Namespace

Drupal\file_entity\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = array();
  $multiple_file_behavior = $this
    ->getSetting('multiple_file_behavior');
  $source_files = array();

  // Because we can have the files grouped in a single video tag, we do a
  // grouping in case the multiple file behavior is not 'tags'.
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $file) {
    if ($file
      ->getMimeTypeType() == 'video') {
      $source_attributes = new Attribute();
      $source_attributes
        ->setAttribute('src', file_create_url($file
        ->getFileUri()));
      $source_attributes
        ->setAttribute('type', $file
        ->getMimeType());
      if ($multiple_file_behavior == 'tags') {
        $source_files[$delta] = array(
          array(
            'file' => $file,
            'source_attributes' => $source_attributes,
          ),
        );
      }
      else {
        $source_files[0][] = array(
          'file' => $file,
          'source_attributes' => $source_attributes,
        );
      }
    }
  }
  if (!empty($source_files)) {

    // Prepare the video attributes according to the settings.
    $video_attributes = new Attribute();
    foreach (array(
      'controls',
      'autoplay',
      'loop',
      'muted',
      'playsinline',
    ) as $attribute) {
      if ($this
        ->getSetting($attribute)) {
        $video_attributes
          ->setAttribute($attribute, $attribute);
      }
    }
    $width = $this
      ->getSetting('width');
    $height = $this
      ->getSetting('height');
    if ($width && $height) {
      $video_attributes
        ->setAttribute('width', $width);
      $video_attributes
        ->setAttribute('height', $height);
    }
    foreach ($source_files as $delta => $files) {
      $elements[$delta] = array(
        '#theme' => 'file_entity_video',
        '#attributes' => $video_attributes,
        '#files' => $files,
      );
      foreach ($files as $file) {
        $this->renderer
          ->addCacheableDependency($elements[$delta], $file['file']);
      }
    }
  }
  return $elements;
}