Verified Commit 458eb456 authored by godotislate's avatar godotislate
Browse files

fix: #3064751 Responsive image formatter does not support URL/Link options

By: idebr
By: ocastle
By: alexpott
By: smustgrave
By: krzysztof domański
By: ravi.shankar
By: godotislate
By: longwave
(cherry picked from commit a85f1db8)
parent 1629df58
Loading
Loading
Loading
Loading
Loading
+26 −57
Original line number Diff line number Diff line
@@ -7,6 +7,7 @@
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
@@ -30,64 +31,31 @@
class ResponsiveImageFormatter extends ImageFormatterBase {

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   * The file url generator.
   */
  protected $responsiveImageStyleStorage;
  protected FileUrlGeneratorInterface $fileUrlGenerator;

  /**
   * 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.
   *
   * @var \Drupal\Core\Utility\LinkGeneratorInterface
   */
  protected $linkGenerator;

  /**
   * Constructs a ResponsiveImageFormatter 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.
   * @param \Drupal\Core\Entity\EntityStorageInterface $responsive_image_style_storage
   *   The responsive image style storage.
   * @param \Drupal\Core\Entity\EntityStorageInterface $image_style_storage
   *   The image style storage.
   * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
   *   The link generator service.
   * @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, EntityStorageInterface $responsive_image_style_storage, EntityStorageInterface $image_style_storage, LinkGeneratorInterface $link_generator, AccountInterface $current_user) {
  public function __construct(
    $plugin_id,
    $plugin_definition,
    FieldDefinitionInterface $field_definition,
    array $settings,
    $label,
    $view_mode,
    array $third_party_settings,
    protected EntityStorageInterface $responsiveImageStyleStorage,
    protected EntityStorageInterface $imageStyleStorage,
    protected LinkGeneratorInterface $linkGenerator,
    protected AccountInterface $currentUser,
    ?FileUrlGeneratorInterface $fileUrlGenerator = NULL,
  ) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);

    $this->responsiveImageStyleStorage = $responsive_image_style_storage;
    $this->imageStyleStorage = $image_style_storage;
    $this->linkGenerator = $link_generator;
    $this->currentUser = $current_user;
    if (!$fileUrlGenerator) {
      @trigger_error('Calling ResponsiveImageFormatter::__construct() without the $fileUrlGenerator argument is deprecated in drupal:11.4.0 and the $fileUrlGenerator argument will be required in drupal:12.0.0. See https://www.drupal.org/node/3291487', E_USER_DEPRECATED);
      $fileUrlGenerator = \Drupal::service('file_url_generator');
    }
    $this->fileUrlGenerator = $fileUrlGenerator;
  }

  /**
@@ -105,7 +73,8 @@ public static function create(ContainerInterface $container, array $configuratio
      $container->get('entity_type.manager')->getStorage('responsive_image_style'),
      $container->get('entity_type.manager')->getStorage('image_style'),
      $container->get('link_generator'),
      $container->get('current_user')
      $container->get('current_user'),
      $container->get('file_url_generator')
    );
  }

@@ -262,7 +231,7 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
      assert($file instanceof FileInterface);
      // Link the <picture> element to the original file.
      if (isset($link_file)) {
        $url = $file->createFileUrl();
        $url = $this->fileUrlGenerator->generate($file->getFileUri());
      }
      // Extract field item attributes for the theme function, and unset them
      // from the $item so that the field template does not re-render them.
+1 −1
Original line number Diff line number Diff line
@@ -13,7 +13,7 @@
 */
#}
{% if url %}
  <a href="{{ url }}">{{ responsive_image }}</a>
  {{ link(responsive_image, url) }}
{% else %}
  {{ responsive_image }}
{% endif %}
+128 −0
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Tests\responsive_image\Kernel;

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\responsive_image\Entity\ResponsiveImageStyle;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the responsive image field rendering.
 */
#[Group('responsive_image')]
#[RunTestsInSeparateProcesses]
class ResponsiveImageFormatterTest extends FieldKernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'breakpoint',
    'file',
    'image',
    'responsive_image',
  ];

  /**
   * The entity type.
   */
  protected string $entityType;

  /**
   * The name of the image field to use for testing.
   */
  protected string $fieldName;

  /**
   * Entity view display.
   */
  protected EntityViewDisplayInterface $display;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $this->installConfig(['field']);
    $this->installEntitySchema('entity_test');
    $this->installEntitySchema('file');
    $this->installSchema('file', ['file_usage']);

    $this->entityType = 'entity_test';
    $bundle = 'entity_test';
    $this->fieldName = $this->randomMachineName();

    // Create a responsive image style.
    ResponsiveImageStyle::create([
      'id' => 'foo',
      'label' => 'Foo',
    ])->save();

    // Create an image field to be used with a responsive image formatter.
    FieldStorageConfig::create([
      'entity_type' => $this->entityType,
      'field_name' => $this->fieldName,
      'type' => 'image',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
    ])->save();

    FieldConfig::create([
      'entity_type' => $this->entityType,
      'field_name' => $this->fieldName,
      'bundle' => $bundle,
      'settings' => [
        'file_extensions' => 'jpg',
      ],
    ])->save();

    /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
    $this->display = EntityViewDisplay::create([
      'targetEntityType' => 'entity_test',
      'bundle' => 'entity_test',
      'mode' => 'default',
    ]);
    $this->display->setComponent($this->fieldName, [
      'type' => 'responsive_image',
      'label' => 'hidden',
      'settings' => [
        'responsive_image_style' => 'foo',
        'image_link' => 'content',
      ],
    ])->save();
  }

  /**
   * Tests Image Formatter URL options handling.
   */
  public function testImageFormatterUrlOptions(): void {
    // Create a test entity with the responsive image field set.
    $entity = EntityTest::create([
      'name' => $this->randomMachineName(),
    ]);
    $entity->{$this->fieldName}->generateSampleItems(1);
    $entity->save();

    // Generate the render array to verify URL options are as expected.
    $build = $this->display->build($entity);
    $this->assertInstanceOf(Url::class, $build[$this->fieldName][0]['#url']);
    $build[$this->fieldName][0]['#url']->setOption('attributes', ['data-attributes-test' => 'test123']);

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');

    $output = $renderer->renderRoot($build[$this->fieldName][0]);
    $this->assertStringContainsString('<a href="' . $entity->toUrl()->toString() . '" data-attributes-test="test123"', (string) $output);
  }

}
+1 −1
Original line number Diff line number Diff line
@@ -11,7 +11,7 @@
 */
#}
{% if url %}
  <a href="{{ url }}">{{ responsive_image }}</a>
  {{ link(responsive_image, url) }}
{% else %}
  {{ responsive_image }}
{% endif %}