media_helper-2.0.0/src/Plugin/Field/FieldFormatter/RenderedImage.php
src/Plugin/Field/FieldFormatter/RenderedImage.php
<?php
namespace Drupal\media_helper\Plugin\Field\FieldFormatter;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\image\ImageStyleStorageInterface;
use Drupal\media\MediaTypeInterface;
use Drupal\media_helper\Service\MediaHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'Media Helper - Rendered Image' formatter.
*
* @FieldFormatter(
* id = "media_helper_rendered_image",
* label = @Translation("Media Helper - Rendered Image"),
* field_types = {
* "entity_reference"
* }
* )
*/
class RenderedImage extends FormatterBase {
/**
* The @entity_type.manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The @media_helper service.
*
* @var \Drupal\media_helper\Service\MediaHelper
*/
protected $mediaHelper;
/**
* Constructs a RenderedImage object.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager, MediaHelper $media_helper) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->entityTypeManager = $entity_type_manager;
$this->mediaHelper = $media_helper;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('entity_type.manager'),
$container->get('media_helper'),
);
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
if ($field_definition->getFieldStorageDefinition()->getSetting('target_type') !== 'media') {
return FALSE;
}
$media_type_storage = \Drupal::entityTypeManager()->getStorage('media_type');
$media_helper = \Drupal::service('media_helper');
assert($media_helper instanceof MediaHelper);
$handler_settings = $field_definition->getSetting('handler_settings');
$target_bundles = $handler_settings['target_bundles'] ?? NULL;
// If target bundle config is empty, assume the field may contain any media bundle on the site.
// The base/default selector behavior in this case is to allow all bundles.
if (!$target_bundles) {
$target_bundles = $media_type_storage->getQuery()
->accessCheck(FALSE)
->execute();
}
foreach ($target_bundles as $target_bundle_id) {
$media_bundle = $media_type_storage->load($target_bundle_id);
assert($media_bundle instanceof MediaTypeInterface || $media_bundle === NULL);
if ($media_bundle && $media_helper->isImageSourceSupported($media_bundle->get('source'))) {
return TRUE;
}
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'image_style' => '',
'css_classes' => '',
'image_attributes' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = [];
$image_styles = $this->entityTypeManager->getStorage('image_style')->loadMultiple();
$image_style_options = array_map(function ($image_style) {
return $image_style->label();
}, $image_styles);
$options = [
'' => $this->t('Default (render per media "default" display mode)'),
$this->t('Image Styles')->__toString() => $image_style_options,
];
if ($this->mediaHelper->isModuleIntegrationEnabled('responsive_image')) {
$responsive_image_styles = array_diff_key(
$this->entityTypeManager->getStorage('responsive_image_style')->loadMultiple(),
$image_style_options
);
if ($responsive_image_styles) {
$options[$this->t('Responsive Image Styles')->__toString()] = array_map(function ($image_style) {
return $image_style->label();
}, $responsive_image_styles);
}
}
$elements['image_style'] = [
'#type' => 'select',
'#title' => $this->t('Image Style'),
'#options' => $options,
'#default_value' => $this->getSetting('image_style'),
];
$elements['css_classes'] = [
'#type' => 'textfield',
'#title' => $this->t('CSS Classes'),
'#description' => $this->t('Separate multiple classes with a space.'),
'#default_value' => $this->getSetting('css_classes'),
];
$elements['image_attributes'] = [
'#type' => 'textfield',
'#title' => $this->t('Attributes'),
'#description' => $this->t('Enter attributes using JSON syntax. In most cases any attributes supplied will be added to the picture tag if this module\'s template override is enabled (<a href="@media_helper_settings_link" target="_blank">check here</a>). A few select attributes such as <em>src</em>, <em>alt</em>, <em>loading</em> and <em>itemprop</em> will always be kept on the img tag even if the template override is in use.', [
'@media_helper_settings_link' => Url::fromRoute('media_helper.settings')->toString(),
]),
'#default_value' => $this->getSetting('image_attributes'),
'#placeholder' => '{ "loading": "eager", "data-attribute": "Value" }',
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
if ($image_style = $this->getSetting('image_style')) {
$summary[] = $this->t('Image Style: @image_style', ['@image_style' => $image_style]);
}
if ($css_classes = $this->getSetting('css_classes')) {
$summary[] = $this->t('CSS Classes: @css_classes', ['@css_classes' => $css_classes]);
}
if ($image_attributes = $this->getSetting('image_attributes')) {
$summary[] = $this->t('Attributes: @image_attributes', ['@image_attributes' => $image_attributes]);
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$image_style = $this->getSetting('image_style');
$css_classes = $this->getSetting('css_classes');
$image_attributes = $this->getSetting('image_attributes');
$image_attributes = $image_attributes ? json_decode($image_attributes, TRUE) ?? [] : [];
$element = [];
foreach ($items as $delta => $item) {
$element[$delta] = $this->mediaHelper->mediaImage($item->entity, $image_style, $css_classes, $image_attributes);
}
return $element;
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
$style_id = $this->getSetting('image_style');
if ($style_id) {
$style = $this->entityTypeManager->getStorage('image_style')->load($style_id);
if (!$style && $this->mediaHelper->isModuleIntegrationEnabled('responsive_image')) {
$style = $this->entityTypeManager->getStorage('responsive_image_style')->load($style_id);
}
if ($style) {
$dependencies[$style->getConfigDependencyKey()][] = $style->getConfigDependencyName();
}
}
return $dependencies;
}
/**
* {@inheritdoc}
*/
public function onDependencyRemoval(array $dependencies) {
$changed = parent::onDependencyRemoval($dependencies);
$style_id = $this->getSetting('image_style');
if ($style_id) {
$style_storage = $this->entityTypeManager->getStorage('image_style');
assert($style_storage instanceof ImageStyleStorageInterface);
$style = $style_storage->load($style_id);
if ($style && !empty($dependencies[$style->getConfigDependencyKey()][$style->getConfigDependencyName()])) {
$replacement_id = $style_storage->getReplacementId($style_id);
// If a valid replacement image style has been provided, use it.
if ($replacement_id && $style_storage->load($replacement_id)) {
$this->setSetting('image_style', $replacement_id);
$changed = TRUE;
}
}
}
return $changed;
}
}
