imagelightbox-8.x-1.3/src/Plugin/Field/FieldFormatter/MediaImagelightboxFormatter.php

src/Plugin/Field/FieldFormatter/MediaImagelightboxFormatter.php
<?php

namespace Drupal\imagelightbox\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\imagelightbox\FileLoaderTrait;
use Drupal\imagelightbox\FileUrlGeneratorTrait;
use Drupal\imagelightbox\ImageStyleLoaderTrait;
use Drupal\media\MediaInterface;

/**
 * Plugin implementation of the 'imagelightbox' formatter.
 *
 * @FieldFormatter(
 *   id = "mediaimagelightbox",
 *   module = "imagelightbox",
 *   label = @Translation("ImageLightBox"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class MediaImageLightboxFormatter extends EntityReferenceFormatterBase {
  use FileUrlGeneratorTrait;
  use ImageStyleLoaderTrait;
  use FileLoaderTrait;

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'image_style' => 'thumbnail',
      'imagelightbox_image_style' => 'large',
      'label' => 'hidden',
      'captions_source' => 'image_title',
      'buttons' => TRUE,
      'inline' => TRUE,
      'lightmode' => FALSE,
      'navigation' => FALSE,
      'activity' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {

    $image_styles = image_style_options(FALSE);

    $element['image_style'] = [
      '#title' => $this->t('Image style'),
      '#type' => 'select',
      '#default_value' => $this->getSetting('image_style'),
      '#empty_option' => $this->t('None (original image)'),
      '#options' => $image_styles,
    ];

    $element['imagelightbox_image_style'] = $element['image_style'];
    $element['imagelightbox_image_style']['#title'] = $this->t('ImageLightBox image style (default)');
    $element['imagelightbox_image_style']['#default_value'] = $this->getSetting('imagelightbox_image_style');

    $element['captions_source'] = [
      '#title' => $this->t('Captions source'),
      '#type' => 'select',
      '#default_value' => $this->getSetting('captions_source'),
      '#options' => $this->captionsSourceOptions(),
    ];

    $element['inline'] = [
      '#title' => $this->t('Display as inline elements'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('inline'),
    ];

    $element['lightmode'] = [
      '#title' => $this->t('Use light theme for the lightbox'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('lightmode'),
    ];

    $element['navigation'] = [
      '#title' => $this->t('Show navigation bar'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('navigation'),
    ];

    $element['activity'] = [
      '#title' => $this->t('Show loading animation'),
      '#type' => 'checkbox',
      '#default_value' => $this->getSetting('activity'),
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {

    $image_styles = image_style_options(FALSE);

    // Unset possible 'No defined styles' option.
    unset($image_styles['']);

    $image_style_setting = $this->getSetting('image_style');
    $style = $image_styles[$image_style_setting] ?? $this->t('Original image');
    $summary[] = $this->t('Image style: @style', ['@style' => $style]);

    $image_style_setting = $this->getSetting('imagelightbox_image_style');
    $style = $image_styles[$image_style_setting] ?? $this->t('Original image');
    $summary[] = $this->t('ImageLightBox image style (default): @style', ['@style' => $style]);

    $captions_source_options = $this->captionsSourceOptions();
    $summary[] = $this->t('Captions source: @captions_source', ['@captions_source' => $captions_source_options[$this->getSetting('captions_source')]]);

    $summary[] = $this->t('Inline: @inline', ['@inline' => $this->getBooleanSettingLabel('inline')]);

    $summary[] = $this->t('Lightmode: @lightmode', ['@lightmode' => $this->getBooleanSettingLabel('lightmode')]);

    $summary[] = $this->t('Navigation: @navigation', ['@navigation' => $this->getBooleanSettingLabel('navigation')]);

    $summary[] = $this->t('Loading animation: @activity', ['@activity' => $this->getBooleanSettingLabel('activity')]);

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {

    // Inject fileUrlGenerator from trait.
    $this->setFileUrlGenerator();

    $elements = [];

    $media_items = $this->getEntitiesToView($items, $langcode);

    // Early opt-out if the field is empty.
    if (empty($media_items)) {
      return $elements;
    }

    $settings = $this->getSettings();
    $cache_tags = [];

    if ($settings['image_style']) {
      $image_style = $this->loadImageStyle($settings['image_style']);
      $cache_tags = $image_style->getCacheTags();
    }

    // Prepare image styles.
    if ($settings['imagelightbox_image_style']) {
      /** @var \Drupal\image\ImageStyleInterface $imagelightbox_image_style */
      $imagelightbox_image_style = $this->loadImageStyle($settings['imagelightbox_image_style']);
    }

    $imagelightbox_image_style_responsive = [];
    if (isset($settings['imagelightbox_image_style_responsive'])) {
      foreach ($settings['imagelightbox_image_style_responsive'] as $preset) {
        if ($preset['width']) {
          $imagelightbox_image_style_responsive[$preset['width']] = $this->loadImageStyle($preset['image_style']);
        }
      }
    }

    /** @var \Drupal\file\MediaInterface[] $media_items */
    foreach ($media_items as $delta => $media) {
      if ($media instanceof MediaInterface) {
        // Get the value from the source field.
        $value = $media->getSource()->getSourceFieldValue($media);

        // If this returns a numeric value, it's a file entity's ID.
        if (is_numeric($value)) {
          $file = $this->loadFile($value);
          if (!empty($file)) {

            // Set url.
            $uri = $file->getFileUri();
            if (!empty($uri)) {
              $default_url = $this->fileUrlGenerator->generateAbsoluteString($uri);
            }

            // Set caption.
            if ($settings['captions_source'] == 'image_alt') {
              $caption = $file->get('alt')->getValue();
            }
            elseif ($settings['captions_source'] == 'image_title' && $file->hasField('title')) {
              $caption = $file->get('title')->getValue();
            }
            else {
              $caption = '';
            }

            // Attributes.
            $link_attributes = [
              'class' => 'lightbox',
              'data-imagelightbox' => 'g',
              'data-ilb2-caption' => $caption,
            ];
            $item_attributes = [
              'class' => 'imagelightbox',
            ];

          }
        }

        $elements[$delta] = [
          '#theme' => 'imagelightbox_formatter',
          '#class' => 'imagelightbox',
          '#item' => $media->get('field_media_image')->first(),
          '#item_attributes' => $item_attributes,
          '#link_attributes' => $link_attributes,
          '#image_style' => $settings['image_style'],
          '#url' => empty($imagelightbox_image_style) ? $default_url : $imagelightbox_image_style->buildUrl($uri),
          '#cache' => [
            'tags' => $cache_tags,
            'contexts' => $cache_contexts ?? "",
          ],
        ];
      };
      $elements['#attached']['drupalSettings']['imagelightbox'] = $settings;
      $elements['#attached']['library'][] = 'imagelightbox/formatter';
      $elements['#attributes']['class'][] = 'imagelightbox';
      if ($settings['inline']) {
        $elements['#attributes']['class'][] = 'container-inline';
      }
    }

    return $elements;
  }

  /**
   * Returns captions source options.
   */
  protected function captionsSourceOptions() {
    return [
      'none' => $this->t('None'),
      'image_title' => $this->t('Image title'),
      'image_alt' => $this->t('Image alt'),
    ];
  }

  /**
   * Returns labels for boolean settings.
   */
  protected function getBooleanSettingLabel($setting) {
    return $this->getSetting($setting) ? $this->t('Yes') : $this->t('No');
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc