You are here

class ImageFieldFormatter in Entity Embed 8

Entity Embed Display reusing image field formatters.

Plugin annotation


@EntityEmbedDisplay(
  id = "image",
  label = @Translation("Image"),
  entity_types = {"file"},
  deriver = "Drupal\entity_embed\Plugin\Derivative\FieldFormatterDeriver",
  field_type = "image",
  provider = "image"
)

Hierarchy

Expanded class hierarchy of ImageFieldFormatter

See also

\Drupal\entity_embed\EntityEmbedDisplay\EntityEmbedDisplayInterface

File

src/Plugin/entity_embed/EntityEmbedDisplay/ImageFieldFormatter.php, line 30

Namespace

Drupal\entity_embed\Plugin\entity_embed\EntityEmbedDisplay
View source
class ImageFieldFormatter extends FileFieldFormatter {

  /**
   * The image factory.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs an ImageFieldFormatter object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager service.
   * @param \Drupal\Core\Field\FormatterPluginManager $formatter_plugin_manager
   *   The field formatter plugin manager.
   * @param \Drupal\Core\TypedData\TypedDataManager $typed_data_manager
   *   The typed data manager.
   * @param \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, FormatterPluginManager $formatter_plugin_manager, TypedDataManager $typed_data_manager, ImageFactory $image_factory, LanguageManagerInterface $language_manager, MessengerInterface $messenger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $formatter_plugin_manager, $typed_data_manager, $language_manager);
    $this->imageFactory = $image_factory;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('plugin.manager.field.formatter'), $container
      ->get('typed_data_manager'), $container
      ->get('image.factory'), $container
      ->get('language_manager'), $container
      ->get('messenger'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldValue() {
    $value = parent::getFieldValue();

    // File field support descriptions, but images do not.
    unset($value['description']);
    $value += array_intersect_key($this
      ->getAttributeValues(), [
      'alt' => '',
      'title' => '',
    ]);
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function access(AccountInterface $account = NULL) {
    return parent::access($account)
      ->andIf($this
      ->isValidImage());
  }

  /**
   * Checks if the image is valid.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   Returns the access result.
   */
  protected function isValidImage() {

    // If entity type is not file we have to return early to prevent fatal in
    // the condition above. Access should already be forbidden at this point,
    // which means this won't have any effect.
    // @see EntityEmbedDisplayBase::access()
    if ($this
      ->getEntityTypeFromContext() != 'file') {
      return AccessResult::forbidden();
    }
    $access = AccessResult::allowed();

    // @todo needs cacheability metadata for getEntityFromContext.
    // @see \Drupal\entity_embed\EntityEmbedDisplay\EntityEmbedDisplayBase::getEntityFromContext()

    /** @var \Drupal\file\FileInterface $entity */
    if ($entity = $this
      ->getEntityFromContext()) {

      // Loading large files is slow, make sure it is an image mime type before
      // doing that.
      list($type, ) = explode('/', $entity
        ->getMimeType(), 2);
      $is_valid_image = FALSE;
      if ($type == 'image') {
        $is_valid_image = $this->imageFactory
          ->get($entity
          ->getFileUri())
          ->isValid();
        if (!$is_valid_image) {
          $this->messenger
            ->addMessage($this
            ->t('The selected image "@image" is invalid.', [
            '@image' => $entity
              ->label(),
          ]), 'error');
        }
      }
      $access = AccessResult::allowedIf($type == 'image' && $is_valid_image)
        ->addCacheableDependency($entity);
    }
    return $access;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    // File field support descriptions, but images do not.
    unset($form['description']);

    // Ensure that the 'Link image to: Content' setting is not available.
    if ($this
      ->getDerivativeId() == 'image') {
      unset($form['image_link']['#options']['content']);
    }
    $entity_element = $form_state
      ->get('entity_element');

    // The alt attribute is *required*, but we allow users to opt-in to empty
    // alt attributes for the very rare edge cases where that is valid by
    // specifying two double quotes as the alternative text in the dialog.
    // However, that *is* stored as an empty alt attribute, so if we're editing
    // an existing image (which means the src attribute is set) and its alt
    // attribute is empty, then we show that as two double quotes in the dialog.
    // @see https://www.drupal.org/node/2307647
    // Alt attribute behavior is taken from the Core image dialog to ensure a
    // consistent UX across various forms.
    // @see Drupal\editor\Form\EditorImageDialog::buildForm()
    $alt = $this
      ->getAttributeValue('alt', '');
    if ($alt === '') {

      // Do not change empty alt text to two double quotes if the previously
      // used Entity Embed Display plugin was not 'image:image'. That means that
      // some other plugin was used so if this image formatter is selected at a
      // later stage, then this should be treated as a new edit. We show two
      // double quotes in place of empty alt text only if that was filled
      // intentionally by the user.
      if (!empty($entity_element) && $entity_element['data-entity-embed-display'] == 'image:image') {
        $alt = MediaImageDecorator::EMPTY_STRING;
      }
    }

    // Add support for editing the alternate and title text attributes.
    $form['alt'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Alternate text'),
      '#default_value' => $alt,
      '#description' => $this
        ->t('This text will be used by screen readers, search engines, or when the image cannot be loaded.'),
      '#parents' => [
        'attributes',
        'alt',
      ],
      '#required' => TRUE,
      '#required_error' => $this
        ->t('Alternative text is required.<br />(Only in rare cases should this be left empty. To create empty alternative text, enter <code>""</code> — two double quotes without any content).'),
      '#maxlength' => 512,
    ];
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Title'),
      '#default_value' => $this
        ->getAttributeValue('title', ''),
      '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'),
      '#parents' => [
        'attributes',
        'title',
      ],
      '#maxlength' => 1024,
    ];
    return $form;
  }

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

    // When the alt attribute is set to two double quotes, transform it to the
    // empty string: two double quotes signify "empty alt attribute". See above.
    if (trim($form_state
      ->getValue([
      'attributes',
      'alt',
    ])) === MediaImageDecorator::EMPTY_STRING) {
      $form_state
        ->setValue([
        'attributes',
        'alt',
      ], '');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
EntityEmbedDisplayBase::$attributes public property The attributes on the embedded entity.
EntityEmbedDisplayBase::$context public property The context for the plugin.
EntityEmbedDisplayBase::$entityTypeManager protected property The entity type manager service.
EntityEmbedDisplayBase::$languageManager protected property The language manager.
EntityEmbedDisplayBase::getAttributeValue public function Gets the value for an attribute.
EntityEmbedDisplayBase::getAttributeValues public function Gets the values for all attributes.
EntityEmbedDisplayBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
EntityEmbedDisplayBase::getConfigurationValue public function Gets a configuration value.
EntityEmbedDisplayBase::getContextValue public function Gets the value for a defined context.
EntityEmbedDisplayBase::getContextValues public function Gets the values for all defined contexts.
EntityEmbedDisplayBase::getEntityFromContext public function Gets the entity from the current context.
EntityEmbedDisplayBase::getEntityTypeFromContext public function Gets the entity type from the current context.
EntityEmbedDisplayBase::getLangcode public function Gets the current language code.
EntityEmbedDisplayBase::hasAttribute public function Checks if an attribute is set.
EntityEmbedDisplayBase::hasContextValue public function Returns whether or not value is set for a defined context.
EntityEmbedDisplayBase::isValidEntityType protected function Validates that this display plugin applies to the current entity type.
EntityEmbedDisplayBase::setAttributes public function Sets the values for all attributes.
EntityEmbedDisplayBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
EntityEmbedDisplayBase::setContextValue public function Sets the value for a defined context.
EntityEmbedDisplayBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
EntityReferenceFieldFormatter::$configFactory protected property The configuration factory.
EntityReferenceFieldFormatter::build public function Builds the renderable array for this Entity Embed display plugin. Overrides FieldFormatterEntityEmbedDisplayBase::build
EntityReferenceFieldFormatter::disableContextualLinks public static function Disables Contextual Links for the embedded media by removing its property.
EntityReferenceFieldFormatter::disableQuickEdit public static function Disables Quick Edit for the embedded media by removing its attributes.
EntityReferenceFieldFormatter::getFieldDefinition public function Get the FieldDefinition object required to render this field's formatter. Overrides FieldFormatterEntityEmbedDisplayBase::getFieldDefinition
EntityReferenceFieldFormatter::isApplicableFieldFormatter protected function Checks if the field formatter is applicable. Overrides FieldFormatterEntityEmbedDisplayBase::isApplicableFieldFormatter
EntityReferenceFieldFormatter::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
FieldFormatterEntityEmbedDisplayBase::$fieldDefinition protected property The field definition.
FieldFormatterEntityEmbedDisplayBase::$fieldFormatter protected property The field formatter.
FieldFormatterEntityEmbedDisplayBase::$formatterPluginManager protected property The field formatter plugin manager.
FieldFormatterEntityEmbedDisplayBase::$typedDataManager protected property The typed data manager.
FieldFormatterEntityEmbedDisplayBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides EntityEmbedDisplayBase::calculateDependencies 1
FieldFormatterEntityEmbedDisplayBase::createFieldDefinition protected function Creates a new faux-field definition.
FieldFormatterEntityEmbedDisplayBase::getFieldFormatter public function Constructs a field formatter. 1
FieldFormatterEntityEmbedDisplayBase::getFieldFormatterId public function Returns the field formatter id. 1
FileFieldFormatter::defaultConfiguration public function Gets default configuration for this plugin. Overrides FieldFormatterEntityEmbedDisplayBase::defaultConfiguration
ImageFieldFormatter::$imageFactory protected property The image factory.
ImageFieldFormatter::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
ImageFieldFormatter::access public function Indicates whether this Entity Embed display can be used. Overrides FieldFormatterEntityEmbedDisplayBase::access
ImageFieldFormatter::buildConfigurationForm public function Form constructor. Overrides FileFieldFormatter::buildConfigurationForm
ImageFieldFormatter::create public static function Creates an instance of the plugin. Overrides EntityReferenceFieldFormatter::create
ImageFieldFormatter::getFieldValue public function Get the field value required to pass into the field formatter. Overrides FileFieldFormatter::getFieldValue
ImageFieldFormatter::isValidImage protected function Checks if the image is valid.
ImageFieldFormatter::submitConfigurationForm public function Form submission handler. Overrides EntityEmbedDisplayBase::submitConfigurationForm
ImageFieldFormatter::__construct public function Constructs an ImageFieldFormatter object. Overrides EntityReferenceFieldFormatter::__construct
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.