sirv-8.x-3.0-beta4/src/Plugin/Field/FieldFormatter/SirvImageFormatterBase.php
src/Plugin/Field/FieldFormatter/SirvImageFormatterBase.php
<?php
namespace Drupal\sirv\Plugin\Field\FieldFormatter;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;
/**
* Base class for Sirv image field formatters.
*/
abstract class SirvImageFormatterBase extends ImageFormatter {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'profile' => '',
'extra_options' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
// Get the parent's elements.
$elements = parent::viewElements($items, $langcode);
// Process each element.
foreach ($elements as &$element) {
$element = $this->processElement($element);
}
return $elements;
}
/**
* Assemble the Sirv image options and add the Sirv settings.
*
* @param array $element
* The element to be processed.
*
* @return array
* The processed element.
*/
protected function processElement(array $element) {
if (!$file = $element['#item']->entity) {
return $element;
}
// Get the field formatter settings.
$settings = $this->getSettings();
// Remove settings not specific to Sirv.
unset($settings['image_style']);
unset($settings['image_link']);
// Assemble the options from the profile and extra options settings.
$options = [];
if (!empty($settings['profile'])) {
$options['profile'] = $settings['profile'];
}
if (!empty($settings['extra_options'])) {
$parts = UrlHelper::parse('?' . $settings['extra_options']);
foreach ($parts['query'] as $key => $value) {
// Convert underscores back to dots in query keys.
$key = str_replace('_', '.', $key);
// Add the query value to the list of options.
$options[$key] = $value;
}
}
unset($settings['profile']);
unset($settings['extra_options']);
$settings = ['options' => $options] + $settings;
// Add the Sirv data to the element.
$element['#sirv'] = [
'settings' => $settings,
];
return $element;
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
// Get the site-wide Sirv settings.
$sirv_settings = \Drupal::config('sirv.settings')->get();
// This formatter should not be available if the Sirv domain is not defined.
return !empty($sirv_settings['domain']) && parent::isApplicable($field_definition);
}
}
