ImageFormatter.php 8.75 KB
Newer Older
1
2
<?php

3
namespace Drupal\image\Plugin\Field\FieldFormatter;
4

5
use Drupal\Core\Entity\EntityStorageInterface;
6
use Drupal\Core\Field\FieldItemListInterface;
7
use Drupal\Core\Field\FieldDefinitionInterface;
8
use Drupal\Core\Link;
9
10
11
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
12
use Drupal\image\Entity\ImageStyle;
13
use Symfony\Component\DependencyInjection\ContainerInterface;
14
use Drupal\Core\Form\FormStateInterface;
15
use Drupal\Core\Cache\Cache;
16
17
18
19

/**
 * Plugin implementation of the 'image' formatter.
 *
20
 * @FieldFormatter(
21
22
23
24
 *   id = "image",
 *   label = @Translation("Image"),
 *   field_types = {
 *     "image"
25
26
27
 *   },
 *   quickedit = {
 *     "editor" = "image"
28
29
30
 *   }
 * )
 */
31
32
33
34
35
36
37
38
39
class ImageFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

40
41
42
  /**
   * The image style entity storage.
   *
43
   * @var \Drupal\image\ImageStyleStorageInterface
44
45
46
   */
  protected $imageStyleStorage;

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  /**
   * 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.
66
67
   * @param \Drupal\Core\Entity\EntityStorageInterface $image_style_storage
   *   The image style storage.
68
   */
69
  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) {
70
71
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->currentUser = $current_user;
72
    $this->imageStyleStorage = $image_style_storage;
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  }

  /**
   * {@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'),
88
      $container->get('entity.manager')->getStorage('image_style')
89
90
    );
  }
91

92
93
94
95
96
97
98
99
100
101
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'image_style' => '',
      'image_link' => '',
    ) + parent::defaultSettings();
  }

102
  /**
103
   * {@inheritdoc}
104
   */
105
  public function settingsForm(array $form, FormStateInterface $form_state) {
106
    $image_styles = image_style_options(FALSE);
107
108
109
110
111
    $description_link = Link::fromTextAndUrl(
      $this->t('Configure Image Styles'),
      Url::fromRoute('entity.image_style.collection')
    );
    $element['image_style'] = [
112
113
114
115
116
      '#title' => t('Image style'),
      '#type' => 'select',
      '#default_value' => $this->getSetting('image_style'),
      '#empty_option' => t('None (original image)'),
      '#options' => $image_styles,
117
118
119
120
      '#description' => $description_link->toRenderable() + [
        '#access' => $this->currentUser->hasPermission('administer image styles')
      ],
    ];
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    $link_types = array(
      'content' => t('Content'),
      'file' => t('File'),
    );
    $element['image_link'] = array(
      '#title' => t('Link image to'),
      '#type' => 'select',
      '#default_value' => $this->getSetting('image_link'),
      '#empty_option' => t('Nothing'),
      '#options' => $link_types,
    );

    return $element;
  }

  /**
137
   * {@inheritdoc}
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
   */
  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'),
    );
    // Display this setting only if image is linked.
    $image_link_setting = $this->getSetting('image_link');
    if (isset($link_types[$image_link_setting])) {
      $summary[] = $link_types[$image_link_setting];
    }

165
    return $summary;
166
167
168
  }

  /**
169
   * {@inheritdoc}
170
   */
171
  public function viewElements(FieldItemListInterface $items, $langcode) {
172
    $elements = array();
173
    $files = $this->getEntitiesToView($items, $langcode);
174
175
176
177
178

    // Early opt-out if the field is empty.
    if (empty($files)) {
      return $elements;
    }
179

180
    $url = NULL;
181
182
183
    $image_link_setting = $this->getSetting('image_link');
    // Check if the formatter involves a link.
    if ($image_link_setting == 'content') {
184
      $entity = $items->getEntity();
185
      if (!$entity->isNew()) {
186
        $url = $entity->urlInfo();
187
      }
188
189
190
191
192
193
    }
    elseif ($image_link_setting == 'file') {
      $link_file = TRUE;
    }

    $image_style_setting = $this->getSetting('image_style');
194
195

    // Collect cache tags to be added for each item in the field.
196
    $base_cache_tags = [];
197
    if (!empty($image_style_setting)) {
198
      $image_style = $this->imageStyleStorage->load($image_style_setting);
199
      $base_cache_tags = $image_style->getCacheTags();
200
201
    }

202
    foreach ($files as $delta => $file) {
203
      $cache_contexts = [];
204
205
      if (isset($link_file)) {
        $image_uri = $file->getFileUri();
206
207
208
209
210
        // @todo Wrap in file_url_transform_relative(). This is currently
        // impossible. As a work-around, we currently add the 'url.site' cache
        // context to ensure different file URLs are generated for different
        // sites in a multisite setup, including HTTP and HTTPS versions of the
        // same site. Fix in https://www.drupal.org/node/2646744.
211
        $url = Url::fromUri(file_create_url($image_uri));
212
        $cache_contexts[] = 'url.site';
213
      }
214
      $cache_tags = Cache::mergeTags($base_cache_tags, $file->getCacheTags());
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

      // Extract field item attributes for the theme function, and unset them
      // from the $item so that the field template does not re-render them.
      $item = $file->_referringItem;
      $item_attributes = $item->_attributes;
      unset($item->_attributes);

      $elements[$delta] = array(
        '#theme' => 'image_formatter',
        '#item' => $item,
        '#item_attributes' => $item_attributes,
        '#image_style' => $image_style_setting,
        '#url' => $url,
        '#cache' => array(
          'tags' => $cache_tags,
230
          'contexts' => $cache_contexts,
231
232
        ),
      );
233
234
235
236
237
    }

    return $elements;
  }

238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
  /**
   * {@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;
  }

275
}