You are here

public function ImageExportFormatter::viewElements in REST Views 8

Same name and namespace in other branches
  1. 2.0.x src/Plugin/Field/FieldFormatter/ImageExportFormatter.php \Drupal\rest_views\Plugin\Field\FieldFormatter\ImageExportFormatter::viewElements()

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 ImageFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/ImageExportFormatter.php, line 90

Class

ImageExportFormatter
Process an image through an image style, and render the URL.

Namespace

Drupal\rest_views\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = parent::viewElements($items, $langcode);
  $alt = $this
    ->getSetting('export_alt');
  $title = $this
    ->getSetting('export_title');
  foreach ($elements as $delta => $element) {
    $item = $element['#item'];
    if (($entity = $item->entity) && empty($item->uri)) {

      /** @var \Drupal\file\FileInterface $entity */
      $uri = $entity
        ->getFileUri();
    }
    else {
      $uri = $item->uri;
    }
    if ($element['#image_style']) {

      /** @var \Drupal\image\ImageStyleInterface $style */
      $style = ImageStyle::load($element['#image_style']);

      // Determine the dimensions of the styled image.
      $dimensions = [
        'width' => $item->width,
        'height' => $item->height,
      ];
      $style
        ->transformDimensions($dimensions, $uri);
      $uri = $style
        ->buildUrl($uri);
    }
    else {
      $uri = file_create_url($uri);
    }
    if ($alt || $title) {
      $data = [
        'url' => $uri,
      ];
      if ($alt) {
        $data['alt'] = $item->alt;
      }
      if ($title && Unicode::strlen($item->title) > 0) {
        $data['title'] = $item->title;
      }
      $elements[$delta] = [
        '#type' => 'data',
        '#data' => SerializedData::create($data),
      ];
    }
    else {
      $elements[$delta] = [
        '#markup' => $uri,
      ];
    }
  }
  return $elements;
}