diff --git a/core/modules/image/config/schema/image.schema.yml b/core/modules/image/config/schema/image.schema.yml index 323220b..cb1a4a8 100644 --- a/core/modules/image/config/schema/image.schema.yml +++ b/core/modules/image/config/schema/image.schema.yml @@ -139,6 +139,20 @@ field.formatter.settings.image: type: string label: 'Image style' +field.formatter.settings.image_url: + type: mapping + label: 'Image URL formatter settings' + mapping: + image_style: + type: string + label: 'Image style' + url_link: + type: boolean + label: 'Link to the image URL' + trim_length: + type: integer + label: 'Trim link text length' + field.widget.settings.image_image: type: mapping label: 'Image field display format settings' diff --git a/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatter.php b/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatter.php index 029e7a5..278ebeb 100644 --- a/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatter.php +++ b/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatter.php @@ -7,17 +7,10 @@ namespace Drupal\image\Plugin\Field\FieldFormatter; -use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Field\FieldItemListInterface; -use Drupal\Core\Field\FieldDefinitionInterface; -use Drupal\Core\Link; -use Drupal\Core\Plugin\ContainerFactoryPluginInterface; -use Drupal\Core\Session\AccountInterface; -use Drupal\Core\Url; -use Drupal\image\Entity\ImageStyle; -use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Cache\Cache; +use Drupal\Core\Url; /** * Plugin implementation of the 'image' formatter. @@ -30,105 +23,32 @@ * } * ) */ -class ImageFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface { - - /** - * The current user. - * - * @var \Drupal\Core\Session\AccountInterface - */ - protected $currentUser; - - /** - * The image style entity storage. - * - * @var \Drupal\image\ImageStyleStorageInterface - */ - protected $imageStyleStorage; - - /** - * Constructs an ImageFormatter object. - * - * @param string $plugin_id - * The plugin_id for the formatter. - * @param mixed $plugin_definition - * The plugin implementation definition. - * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition - * The definition of the field to which the formatter is associated. - * @param array $settings - * The formatter settings. - * @param string $label - * The formatter label display setting. - * @param string $view_mode - * The view mode. - * @param array $third_party_settings - * Any third party settings settings. - * @param \Drupal\Core\Session\AccountInterface $current_user - * The current user. - */ - public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, EntityStorageInterface $image_style_storage) { - parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings); - $this->currentUser = $current_user; - $this->imageStyleStorage = $image_style_storage; - } - - /** - * {@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('current_user'), - $container->get('entity.manager')->getStorage('image_style') - ); - } +class ImageFormatter extends ImageFormatterBase { /** * {@inheritdoc} */ public static function defaultSettings() { - return array( - 'image_style' => '', - 'image_link' => '', - ) + parent::defaultSettings(); + return ['image_link' => ''] + parent::defaultSettings(); } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { - $image_styles = image_style_options(FALSE); - $description_link = Link::fromTextAndUrl( - $this->t('Configure Image Styles'), - Url::fromRoute('entity.image_style.collection') - ); - $element['image_style'] = [ - '#title' => t('Image style'), - '#type' => 'select', - '#default_value' => $this->getSetting('image_style'), - '#empty_option' => t('None (original image)'), - '#options' => $image_styles, - '#description' => $description_link->toRenderable() + [ - '#access' => $this->currentUser->hasPermission('administer image styles') - ], + $element = parent::settingsForm($form, $form_state); + + $link_types = [ + 'content' => $this->t('Content'), + 'file' => $this->t('File'), ]; - $link_types = array( - 'content' => t('Content'), - 'file' => t('File'), - ); - $element['image_link'] = array( - '#title' => t('Link image to'), + $element['image_link'] = [ + '#title' => $this->t('Link image to'), '#type' => 'select', '#default_value' => $this->getSetting('image_link'), - '#empty_option' => t('Nothing'), + '#empty_option' => $this->t('Nothing'), '#options' => $link_types, - ); + ]; return $element; } @@ -137,28 +57,14 @@ public function settingsForm(array $form, FormStateInterface $form_state) { * {@inheritdoc} */ public function settingsSummary() { - $summary = array(); - - $image_styles = image_style_options(FALSE); - // Unset possible 'No defined styles' option. - unset($image_styles['']); - // Styles could be lost because of enabled/disabled modules that defines - // their styles in code. - $image_style_setting = $this->getSetting('image_style'); - if (isset($image_styles[$image_style_setting])) { - $summary[] = t('Image style: @style', array('@style' => $image_styles[$image_style_setting])); - } - else { - $summary[] = t('Original image'); - } - - $link_types = array( - 'content' => t('Linked to content'), - 'file' => t('Linked to file'), - ); + $summary = parent::settingsSummary(); + $link_types = [ + 'content' => $this->t('Linked to content'), + 'file' => $this->t('Linked to file'), + ]; // Display this setting only if image is linked. $image_link_setting = $this->getSetting('image_link'); - if (isset($link_types[$image_link_setting])) { + if ($image_link_setting && isset($link_types[$image_link_setting])) { $summary[] = $link_types[$image_link_setting]; } @@ -170,6 +76,7 @@ public function settingsSummary() { */ public function viewElements(FieldItemListInterface $items, $langcode) { $elements = array(); + /** @var \Drupal\file\Entity\File[] $files */ $files = $this->getEntitiesToView($items, $langcode); // Early opt-out if the field is empty. @@ -235,41 +142,4 @@ public function viewElements(FieldItemListInterface $items, $langcode) { return $elements; } - /** - * {@inheritdoc} - */ - public function calculateDependencies() { - $dependencies = parent::calculateDependencies(); - $style_id = $this->getSetting('image_style'); - /** @var \Drupal\image\ImageStyleInterface $style */ - if ($style_id && $style = ImageStyle::load($style_id)) { - // If this formatter uses a valid image style to display the image, add - // the image style configuration entity as dependency of this formatter. - $dependencies[$style->getConfigDependencyKey()][] = $style->getConfigDependencyName(); - } - return $dependencies; - } - - /** - * {@inheritdoc} - */ - public function onDependencyRemoval(array $dependencies) { - $changed = parent::onDependencyRemoval($dependencies); - $style_id = $this->getSetting('image_style'); - /** @var \Drupal\image\ImageStyleInterface $style */ - if ($style_id && $style = ImageStyle::load($style_id)) { - if (!empty($dependencies[$style->getConfigDependencyKey()][$style->getConfigDependencyName()])) { - $replacement_id = $this->imageStyleStorage->getReplacementId($style_id); - // If a valid replacement has been provided in the storage, replace the - // image style with the replacement and signal that the formatter plugin - // settings were updated. - if ($replacement_id && ImageStyle::load($replacement_id)) { - $this->setSetting('image_style', $replacement_id); - $changed = TRUE; - } - } - } - return $changed; - } - } diff --git a/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatterBase.php b/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatterBase.php index 899aa49..e54c4e1 100644 --- a/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatterBase.php +++ b/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatterBase.php @@ -7,14 +7,141 @@ namespace Drupal\image\Plugin\Field\FieldFormatter; +use Drupal\Core\Access\AccessResult; +use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Field\EntityReferenceFieldItemListInterface; +use Drupal\Core\Field\FieldDefinitionInterface; +use Drupal\Core\Form\FormStateInterface; +use Drupal\Core\Link; +use Drupal\Core\Plugin\ContainerFactoryPluginInterface; +use Drupal\Core\Session\AccountInterface; +use Drupal\Core\Url; use Drupal\field\FieldConfigInterface; use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase; +use Drupal\image\Entity\ImageStyle; +use Symfony\Component\DependencyInjection\ContainerInterface; /** * Base class for image file formatters. */ -abstract class ImageFormatterBase extends FileFormatterBase { +abstract class ImageFormatterBase extends FileFormatterBase implements ContainerFactoryPluginInterface { + + /** + * The current user service. + * + * @var \Drupal\Core\Session\AccountInterface + */ + protected $currentUser; + + /** + * The image style entity storage. + * + * @var \Drupal\Core\Entity\EntityStorageInterface + */ + protected $imageStyleStorage; + + /** + * The entity repository service. + * + * @var \Drupal\Core\Entity\EntityRepositoryInterface + */ + protected $entityRepository; + + /** + * Constructs an ImageFormatterBase object. + * + * @param string $plugin_id + * The plugin_id for the formatter. + * @param mixed $plugin_definition + * The plugin implementation definition. + * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition + * The definition of the field to which the formatter is associated. + * @param array $settings + * The formatter settings. + * @param string $label + * The formatter label setting. + * @param string $view_mode + * The view mode. + * @param array $third_party_settings + * Any third party settings. + * @param \Drupal\Core\Session\AccountInterface $current_user + * The current user. + * @param \Drupal\Core\Entity\EntityStorageInterface $image_style_storage + * The image style entity storage. + */ + public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, EntityStorageInterface $image_style_storage) { + parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings); + $this->currentUser = $current_user; + $this->imageStyleStorage = $image_style_storage; + } + + /** + * {@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('current_user'), + $container->get('entity_type.manager')->getStorage('image_style') + ); + } + + /** + * {@inheritdoc} + */ + public static function defaultSettings() { + return ['image_style' => ''] + parent::defaultSettings(); + } + + /** + * {@inheritdoc} + */ + public function settingsForm(array $form, FormStateInterface $form_state) { + $image_styles = image_style_options(FALSE); + $description_link = Link::fromTextAndUrl( + $this->t('Configure image styles'), + Url::fromRoute('entity.image_style.collection') + ); + $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, + '#description' => $description_link->toRenderable() + [ + '#access' => AccessResult::allowedIfHasPermission($this->currentUser, 'administer image styles'), + ], + ]; + + return $element; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + $summary = []; + + $image_styles = image_style_options(FALSE); + // Unset possible 'No defined styles' option. + unset($image_styles['']); + + $image_style_setting = $this->getSetting('image_style'); + if (isset($image_styles[$image_style_setting])) { + $summary[] = $this->t('Image style: @style', ['@style' => $image_styles[$image_style_setting]]); + } + else { + $summary[] = $this->t('Original image'); + } + + return $summary; + } /** * {@inheritdoc} @@ -28,12 +155,12 @@ protected function getEntitiesToView(EntityReferenceFieldItemListInterface $item if (empty($default_image['uuid']) && $this->fieldDefinition instanceof FieldConfigInterface) { $default_image = $this->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image'); } - if (!empty($default_image['uuid']) && $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid'])) { + if (!empty($default_image['uuid']) && $file = $this->getEntityRepository()->loadEntityByUuid('file', $default_image['uuid'])) { // Clone the FieldItemList into a runtime-only object for the formatter, // so that the fallback image can be rendered without affecting the // field values in the entity being rendered. $items = clone $items; - $items->setValue(array( + $items->setValue([ 'target_id' => $file->id(), 'alt' => $default_image['alt'], 'title' => $default_image['title'], @@ -42,7 +169,7 @@ protected function getEntitiesToView(EntityReferenceFieldItemListInterface $item 'entity' => $file, '_loaded' => TRUE, '_is_default' => TRUE, - )); + ]); $file->_referringItem = $items[0]; } } @@ -50,4 +177,55 @@ protected function getEntitiesToView(EntityReferenceFieldItemListInterface $item return parent::getEntitiesToView($items, $langcode); } + /** + * {@inheritdoc} + */ + public function calculateDependencies() { + $dependencies = parent::calculateDependencies(); + $style_id = $this->getSetting('image_style'); + /** @var \Drupal\image\ImageStyleInterface $style */ + if ($style_id && $style = ImageStyle::load($style_id)) { + // If this formatter uses a valid image style to display the image, add + // the image style configuration entity as dependency of this formatter. + $dependencies[$style->getConfigDependencyKey()][] = $style->getConfigDependencyName(); + } + return $dependencies; + } + + /** + * {@inheritdoc} + */ + public function onDependencyRemoval(array $dependencies) { + $changed = parent::onDependencyRemoval($dependencies); + $style_id = $this->getSetting('image_style'); + /** @var \Drupal\image\ImageStyleInterface $style */ + if ($style_id && $style = ImageStyle::load($style_id)) { + if (!empty($dependencies[$style->getConfigDependencyKey()][$style->getConfigDependencyName()])) { + $replacement_id = $this->imageStyleStorage->getReplacementId($style_id); + // If a valid replacement has been provided in the storage, replace the + // image style with the replacement and signal that the formatter plugin + // settings were updated. + if ($replacement_id && ImageStyle::load($replacement_id)) { + $this->setSetting('image_style', $replacement_id); + $changed = TRUE; + } + } + } + return $changed; + } + + /** + * Returns the entity repository service. + * + * @return \Drupal\Core\Entity\EntityRepositoryInterface + * + * @todo Inject this service in constructor, in Drupal 9.0.x. + */ + protected function getEntityRepository() { + if (!isset($this->entityRepository)) { + $this->entityRepository = \Drupal::service('entity.repository'); + } + return $this->entityRepository; + } + } diff --git a/core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php b/core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php new file mode 100644 index 0000000..8c7efa9 --- /dev/null +++ b/core/modules/image/src/Plugin/Field/FieldFormatter/ImageUrlFormatter.php @@ -0,0 +1,139 @@ + FALSE, + 'trim_length' => 80, + ] + parent::defaultSettings(); + } + + /** + * {@inheritdoc} + */ + public function settingsForm(array $form, FormStateInterface $form_state) { + $element = parent::settingsForm($form, $form_state); + + $element['url_link'] = [ + '#type' => 'checkbox', + '#title' => $this->t('Provide link'), + '#description' => $this->t('If checked, the URL to image will get a click-able link otherwise, the plain URL will be displayed.'), + '#default_value' => $this->getSetting('url_link'), + ]; + $field_name = $this->fieldDefinition->getName(); + $element['trim_length'] = [ + '#type' => 'number', + '#title' => $this->t('Trim link text length'), + '#field_suffix' => $this->t('characters'), + '#default_value' => $this->getSetting('trim_length'), + '#min' => 1, + '#description' => $this->t('Leave blank to allow unlimited link text length.'), + '#states' => [ + 'visible' => [ + ':input[name="fields[' . $field_name . '][settings_edit_form][settings][url_link]"]' => ['checked' => TRUE], + ], + ], + ]; + + return $element; + } + + /** + * {@inheritdoc} + */ + public function settingsSummary() { + $summary = parent::settingsSummary(); + + if (!$this->getSetting('url_link')) { + $summary[] = $this->t('Show URL as plain-text'); + } + else { + $trim_length = $this->getSetting('trim_length'); + if (empty($trim_length)) { + $summary[] = $this->t('Show URL as link'); + } + else { + $summary[] = $this->t('Show URL as link trimmed to @limit characters', ['@limit' => $trim_length]); + } + } + + return $summary; + } + + /** + * {@inheritdoc} + */ + public function viewElements(FieldItemListInterface $items, $langcode) { + $elements = []; + + /** + * @var \Drupal\file\Entity\File[] $images + * @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items + */ + if (empty($images = $this->getEntitiesToView($items, $langcode))) { + // Early opt-out if the field is empty. + return $elements; + } + + /** @var \Drupal\image\ImageStyleInterface $image_style */ + $image_style = $this->imageStyleStorage->load($this->getSetting('image_style')); + + foreach ($images as $delta => $image) { + $image_uri = $image->getFileUri(); + $url = $image_style ? $image_style->buildUrl($image_uri) : file_create_url($image_uri); + + // Add cacheable metadata from the image and image style. + $cacheable_metadata = CacheableMetadata::createFromObject($image); + if ($image_style) { + $cacheable_metadata->addCacheableDependency(CacheableMetadata::createFromObject($image_style)); + } + + if (!$this->getSetting('url_link')) { + // Plain text URL. + $elements[$delta] = ['#markup' => $url]; + } + else { + // Link URL. + $text = $url; + // Trim the link text to the desired length. + if (!empty($trim_length = $this->getSetting('trim_length'))) { + $text = Unicode::truncate($text, $trim_length, FALSE, TRUE); + } + $elements[$delta] = Link::fromTextAndUrl($text, Url::fromUri($url))->toRenderable(); + } + $cacheable_metadata->applyTo($elements[$delta]); + } + + return $elements; + } + +} diff --git a/core/modules/image/src/Tests/ImageFieldDisplayTest.php b/core/modules/image/src/Tests/ImageFieldDisplayTest.php index 2ae0fa4..c824ec4 100644 --- a/core/modules/image/src/Tests/ImageFieldDisplayTest.php +++ b/core/modules/image/src/Tests/ImageFieldDisplayTest.php @@ -7,6 +7,7 @@ namespace Drupal\image\Tests; +use Drupal\Component\Utility\Unicode; use Drupal\Core\Field\FieldStorageDefinitionInterface; use Drupal\field\Entity\FieldStorageConfig; use Drupal\user\RoleInterface; @@ -93,6 +94,7 @@ function _testImageFieldFormatters($scheme) { // Save node. $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt); $node_storage->resetCache(array($nid)); + /** @var \Drupal\node\Entity\Node $node */ $node = $node_storage->load($nid); // Test that the default formatter is being used. @@ -204,6 +206,38 @@ function _testImageFieldFormatters($scheme) { $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri)); $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.'); } + + // Test the image URL formatter without an image style. + $display_options = [ + 'type' => 'image_url', + 'settings' => [ + 'image_style' => '', + 'url_link' => FALSE, + 'trim_length' => 80, + ], + ]; + $expected_url = file_create_url($image_uri); + $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']); + + // Test the image URL formatter without an image style. + $display_options['settings']['image_style'] = 'thumbnail'; + $expected_url = ImageStyle::load('thumbnail')->buildUrl($image_uri); + $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']); + + // Test the image URL formatter with an image style with link. + $display_options['settings']['url_link'] = TRUE; + $display_options['settings']['trim_length'] = 0; + + $expected_output = '' . $expected_url . ''; + $this->assertEqual($expected_output, (string) $renderer->renderRoot($node->{$field_name}->view($display_options)[0])); + + // Test the image URL formatter with an image style with link and trimmed + // link text. + $display_options['settings']['trim_length'] = 10; + + $expected_link_text = Unicode::truncate($expected_url, 10, FALSE, TRUE); + $expected_output = '' . $expected_link_text . ''; + $this->assertEqual($expected_output, (string) $renderer->renderRoot($node->{$field_name}->view($display_options)[0])); } /** diff --git a/core/modules/responsive_image/src/Plugin/Field/FieldFormatter/ResponsiveImageFormatter.php b/core/modules/responsive_image/src/Plugin/Field/FieldFormatter/ResponsiveImageFormatter.php index e66cb82..6dc8620 100644 --- a/core/modules/responsive_image/src/Plugin/Field/FieldFormatter/ResponsiveImageFormatter.php +++ b/core/modules/responsive_image/src/Plugin/Field/FieldFormatter/ResponsiveImageFormatter.php @@ -12,7 +12,6 @@ use Drupal\Core\Field\FieldDefinitionInterface; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Form\FormStateInterface; -use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\Core\Url; use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase; use Symfony\Component\DependencyInjection\ContainerInterface; @@ -30,27 +29,13 @@ * } * ) */ -class ResponsiveImageFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface { +class ResponsiveImageFormatter extends ImageFormatterBase { /** * @var EntityStorageInterface */ protected $responsiveImageStyleStorage; - /* - * The image style entity storage. - * - * @var \Drupal\Core\Entity\EntityStorageInterface - */ - protected $imageStyleStorage; - - /** - * The current user. - * - * @var \Drupal\Core\Session\AccountInterface - */ - protected $currentUser; - /** * The link generator. * @@ -85,12 +70,9 @@ class ResponsiveImageFormatter extends ImageFormatterBase implements ContainerFa * The current user. */ public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityStorageInterface $responsive_image_style_storage, EntityStorageInterface $image_style_storage, LinkGeneratorInterface $link_generator, AccountInterface $current_user) { - parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings); - + parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings, $current_user, $image_style_storage); $this->responsiveImageStyleStorage = $responsive_image_style_storage; - $this->imageStyleStorage = $image_style_storage; $this->linkGenerator = $link_generator; - $this->currentUser = $current_user; } /** @@ -119,7 +101,7 @@ public static function defaultSettings() { return array( 'responsive_image_style' => '', 'image_link' => '', - ) + parent::defaultSettings(); + ); } /**