You are here

public function ImageEmbedDataFormatter::viewElements in Formatter Suite 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 ImageFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/ImageEmbedDataFormatter.php, line 204

Class

ImageEmbedDataFormatter
Embeds an image as a data URL instead of a file URL.

Namespace

Drupal\formatter_suite\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langCode) {

  // Get current settings.
  $maximumEmbedWidth = $this
    ->getSetting('maximumEmbedWidth');
  $maximumEmbedHeight = $this
    ->getSetting('maximumEmbedHeight');

  // Sanitize & validate.
  //
  // Security: The maximum embed width and height have been entered by
  // an administrator. They both should be simple integers and should
  // not include any HTML or HTML entities.
  //
  // Parsing these as integers ignores any extra text that may be in
  // the value.
  if (isset($maximumEmbedWidth) === TRUE) {
    $maximumEmbedWidth = (int) $maximumEmbedWidth;
  }
  else {
    $maximumEmbedWidth = 0;
  }
  if (isset($maximumEmbedHeight) === TRUE) {
    $maximumEmbedHeight = (int) $maximumEmbedHeight;
  }
  else {
    $maximumEmbedHeight = 0;
  }

  // The parent image module does very little processing within the
  // formatter. Instead, it sets a theme template and later processing
  // of the template sets up the image's URL, including possibly use of
  // an image style.
  //
  // Let the parent class do its processing. The returned array has one
  // entry per item and a configuration that invokes the image module's
  // 'image_formatter' theme.
  //
  // If the items list is empty, the parent class looks for a default
  // image for the field and, if any, fills it in. The resulting
  // $elements array will only be empty if there was no default image.
  $elements = parent::viewElements($items, $langCode);
  if (empty($elements) === TRUE) {
    return [];
  }

  // Loop through results from the parent class and swap the theme
  // to point to our own 'formatter_suite_image_formatter'. Add the
  // configured maximum width and height. Then let theme handling
  // take over to handle inlining images.
  foreach ($elements as $delta => $element) {
    if (isset($elements[$delta]) === TRUE && isset($elements[$delta]['#theme']) === TRUE) {
      $elements[$delta]['#theme'] = 'formatter_suite_image_embed_formatter';
      $elements[$delta]['#maximumEmbedWidth'] = $maximumEmbedWidth;
      $elements[$delta]['#maximumEmbedHeight'] = $maximumEmbedHeight;
    }
  }
  return $elements;
}