ImageExportFormatter.php in REST Views 8
File
src/Plugin/Field/FieldFormatter/ImageExportFormatter.php
View source
<?php
namespace Drupal\rest_views\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;
use Drupal\rest_views\SerializedData;
class ImageExportFormatter extends ImageFormatter {
public static function defaultSettings() {
$settings = [
'export_alt' => FALSE,
'export_title' => FALSE,
] + parent::defaultSettings();
unset($settings['image_link']);
return $settings;
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
unset($form['image_link']);
$alt = $this
->getFieldSetting('alt_field');
$title = $this
->getFieldSetting('title_field');
if ($alt) {
$form['export_alt'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Export <em>Alt</em> field'),
'#description' => $this
->t('Enabling this will export an object instead of a string.'),
'#default_value' => $this
->getSetting('export_alt'),
];
}
else {
$form['export_alt'] = [
'#type' => 'value',
'#value' => FALSE,
];
}
if ($title) {
$form['export_title'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Export <em>Title</em> field'),
'#description' => $this
->t('Enabling this will export an object instead of a string.'),
'#default_value' => $this
->getSetting('export_title'),
];
}
else {
$form['export_title'] = [
'#type' => 'value',
'#value' => FALSE,
];
}
return $form;
}
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this
->getSetting('export_alt')) {
$summary[] = $this
->t('<em>Alt</em> field is exported.');
}
if ($this
->getSetting('export_title')) {
$summary[] = $this
->t('<em>Title</em> field is exported.');
}
return $summary;
}
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)) {
$uri = $entity
->getFileUri();
}
else {
$uri = $item->uri;
}
if ($element['#image_style']) {
$style = ImageStyle::load($element['#image_style']);
$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;
}
}