6d9b7fa2fa3283dc8226c57d06bca681a81864b4
[yaffs-website] / web / core / modules / responsive_image / src / Plugin / Field / FieldFormatter / ResponsiveImageFormatter.php
1 <?php
2
3 namespace Drupal\responsive_image\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Entity\EntityStorageInterface;
7 use Drupal\Core\Field\FieldDefinitionInterface;
8 use Drupal\Core\Field\FieldItemListInterface;
9 use Drupal\Core\Form\FormStateInterface;
10 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
11 use Drupal\Core\Url;
12 use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase;
13 use Drupal\responsive_image\Entity\ResponsiveImageStyle;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15 use Drupal\Core\Session\AccountInterface;
16 use Drupal\Core\Utility\LinkGeneratorInterface;
17
18 /**
19  * Plugin for responsive image formatter.
20  *
21  * @FieldFormatter(
22  *   id = "responsive_image",
23  *   label = @Translation("Responsive image"),
24  *   field_types = {
25  *     "image",
26  *   },
27  *   quickedit = {
28  *     "editor" = "image"
29  *   }
30  * )
31  */
32 class ResponsiveImageFormatter extends ImageFormatterBase implements ContainerFactoryPluginInterface {
33
34   /**
35    * @var EntityStorageInterface
36    */
37   protected $responsiveImageStyleStorage;
38
39   /*
40    * The image style entity storage.
41    *
42    * @var \Drupal\Core\Entity\EntityStorageInterface
43    */
44   protected $imageStyleStorage;
45
46   /**
47    * The current user.
48    *
49    * @var \Drupal\Core\Session\AccountInterface
50    */
51   protected $currentUser;
52
53   /**
54    * The link generator.
55    *
56    * @var \Drupal\Core\Utility\LinkGeneratorInterface
57    */
58   protected $linkGenerator;
59
60   /**
61    * Constructs a ResponsiveImageFormatter object.
62    *
63    * @param string $plugin_id
64    *   The plugin_id for the formatter.
65    * @param mixed $plugin_definition
66    *   The plugin implementation definition.
67    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
68    *   The definition of the field to which the formatter is associated.
69    * @param array $settings
70    *   The formatter settings.
71    * @param string $label
72    *   The formatter label display setting.
73    * @param string $view_mode
74    *   The view mode.
75    * @param array $third_party_settings
76    *   Any third party settings.
77    * @param \Drupal\Core\Entity\EntityStorageInterface $responsive_image_style_storage
78    *   The responsive image style storage.
79    * @param \Drupal\Core\Entity\EntityStorageInterface $image_style_storage
80    *   The image style storage.
81    * @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
82    *   The link generator service.
83    * @param \Drupal\Core\Session\AccountInterface $current_user
84    *   The current user.
85    */
86   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) {
87     parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
88
89     $this->responsiveImageStyleStorage = $responsive_image_style_storage;
90     $this->imageStyleStorage = $image_style_storage;
91     $this->linkGenerator = $link_generator;
92     $this->currentUser = $current_user;
93   }
94
95   /**
96    * {@inheritdoc}
97    */
98   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
99     return new static(
100       $plugin_id,
101       $plugin_definition,
102       $configuration['field_definition'],
103       $configuration['settings'],
104       $configuration['label'],
105       $configuration['view_mode'],
106       $configuration['third_party_settings'],
107       $container->get('entity.manager')->getStorage('responsive_image_style'),
108       $container->get('entity.manager')->getStorage('image_style'),
109       $container->get('link_generator'),
110       $container->get('current_user')
111     );
112   }
113
114   /**
115    * {@inheritdoc}
116    */
117   public static function defaultSettings() {
118     return [
119       'responsive_image_style' => '',
120       'image_link' => '',
121     ] + parent::defaultSettings();
122   }
123
124   /**
125    * {@inheritdoc}
126    */
127   public function settingsForm(array $form, FormStateInterface $form_state) {
128     $responsive_image_options = [];
129     $responsive_image_styles = $this->responsiveImageStyleStorage->loadMultiple();
130     if ($responsive_image_styles && !empty($responsive_image_styles)) {
131       foreach ($responsive_image_styles as $machine_name => $responsive_image_style) {
132         if ($responsive_image_style->hasImageStyleMappings()) {
133           $responsive_image_options[$machine_name] = $responsive_image_style->label();
134         }
135       }
136     }
137
138     $elements['responsive_image_style'] = [
139       '#title' => t('Responsive image style'),
140       '#type' => 'select',
141       '#default_value' => $this->getSetting('responsive_image_style'),
142       '#required' => TRUE,
143       '#options' => $responsive_image_options,
144       '#description' => [
145         '#markup' => $this->linkGenerator->generate($this->t('Configure Responsive Image Styles'), new Url('entity.responsive_image_style.collection')),
146         '#access' => $this->currentUser->hasPermission('administer responsive image styles'),
147         ],
148     ];
149
150     $link_types = [
151       'content' => t('Content'),
152       'file' => t('File'),
153     ];
154     $elements['image_link'] = [
155       '#title' => t('Link image to'),
156       '#type' => 'select',
157       '#default_value' => $this->getSetting('image_link'),
158       '#empty_option' => t('Nothing'),
159       '#options' => $link_types,
160     ];
161
162     return $elements;
163   }
164
165   /**
166    * {@inheritdoc}
167    */
168   public function settingsSummary() {
169     $summary = [];
170
171     $responsive_image_style = $this->responsiveImageStyleStorage->load($this->getSetting('responsive_image_style'));
172     if ($responsive_image_style) {
173       $summary[] = t('Responsive image style: @responsive_image_style', ['@responsive_image_style' => $responsive_image_style->label()]);
174
175       $link_types = [
176         'content' => t('Linked to content'),
177         'file' => t('Linked to file'),
178       ];
179       // Display this setting only if image is linked.
180       if (isset($link_types[$this->getSetting('image_link')])) {
181         $summary[] = $link_types[$this->getSetting('image_link')];
182       }
183     }
184     else {
185       $summary[] = t('Select a responsive image style.');
186     }
187
188     return $summary;
189   }
190
191   /**
192    * {@inheritdoc}
193    */
194   public function viewElements(FieldItemListInterface $items, $langcode) {
195     $elements = [];
196     $files = $this->getEntitiesToView($items, $langcode);
197
198     // Early opt-out if the field is empty.
199     if (empty($files)) {
200       return $elements;
201     }
202
203     $url = NULL;
204     // Check if the formatter involves a link.
205     if ($this->getSetting('image_link') == 'content') {
206       $entity = $items->getEntity();
207       if (!$entity->isNew()) {
208         $url = $entity->urlInfo();
209       }
210     }
211     elseif ($this->getSetting('image_link') == 'file') {
212       $link_file = TRUE;
213     }
214
215     // Collect cache tags to be added for each item in the field.
216     $responsive_image_style = $this->responsiveImageStyleStorage->load($this->getSetting('responsive_image_style'));
217     $image_styles_to_load = [];
218     $cache_tags = [];
219     if ($responsive_image_style) {
220       $cache_tags = Cache::mergeTags($cache_tags, $responsive_image_style->getCacheTags());
221       $image_styles_to_load = $responsive_image_style->getImageStyleIds();
222     }
223
224     $image_styles = $this->imageStyleStorage->loadMultiple($image_styles_to_load);
225     foreach ($image_styles as $image_style) {
226       $cache_tags = Cache::mergeTags($cache_tags, $image_style->getCacheTags());
227     }
228
229     foreach ($files as $delta => $file) {
230       // Link the <picture> element to the original file.
231       if (isset($link_file)) {
232         $url = file_url_transform_relative(file_create_url($file->getFileUri()));
233       }
234       // Extract field item attributes for the theme function, and unset them
235       // from the $item so that the field template does not re-render them.
236       $item = $file->_referringItem;
237       $item_attributes = $item->_attributes;
238       unset($item->_attributes);
239
240       $elements[$delta] = [
241         '#theme' => 'responsive_image_formatter',
242         '#item' => $item,
243         '#item_attributes' => $item_attributes,
244         '#responsive_image_style_id' => $responsive_image_style ? $responsive_image_style->id() : '',
245         '#url' => $url,
246         '#cache' => [
247           'tags' => $cache_tags,
248         ],
249       ];
250     }
251     return $elements;
252   }
253
254   /**
255    * {@inheritdoc}
256    */
257   public function calculateDependencies() {
258     $dependencies = parent::calculateDependencies();
259     $style_id = $this->getSetting('responsive_image_style');
260     /** @var \Drupal\responsive_image\ResponsiveImageStyleInterface $style */
261     if ($style_id && $style = ResponsiveImageStyle::load($style_id)) {
262       // Add the responsive image style as dependency.
263       $dependencies[$style->getConfigDependencyKey()][] = $style->getConfigDependencyName();
264     }
265     return $dependencies;
266   }
267
268 }