8ef7792d6b69f26002df949a5bd8d06a3f037feb
[yaffs-website] / web / core / modules / media / src / Plugin / Field / FieldFormatter / MediaThumbnailFormatter.php
1 <?php
2
3 namespace Drupal\media\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Session\AccountInterface;
9 use Drupal\image\ImageStyleStorageInterface;
10 use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;
11 use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
12 use Drupal\Core\Render\RendererInterface;
13 use Drupal\media\MediaInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15 use Drupal\Core\Field\FieldDefinitionInterface;
16
17 /**
18  * Plugin implementation of the 'media_thumbnail' formatter.
19  *
20  * @FieldFormatter(
21  *   id = "media_thumbnail",
22  *   label = @Translation("Thumbnail"),
23  *   field_types = {
24  *     "entity_reference"
25  *   }
26  * )
27  */
28 class MediaThumbnailFormatter extends ImageFormatter {
29
30   /**
31    * The renderer service.
32    *
33    * @var \Drupal\Core\Render\RendererInterface
34    */
35   protected $renderer;
36
37   /**
38    * Constructs an MediaThumbnailFormatter object.
39    *
40    * @param string $plugin_id
41    *   The plugin_id for the formatter.
42    * @param mixed $plugin_definition
43    *   The plugin implementation definition.
44    * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
45    *   The definition of the field to which the formatter is associated.
46    * @param array $settings
47    *   The formatter settings.
48    * @param string $label
49    *   The formatter label display setting.
50    * @param string $view_mode
51    *   The view mode.
52    * @param array $third_party_settings
53    *   Any third party settings settings.
54    * @param \Drupal\Core\Session\AccountInterface $current_user
55    *   The current user.
56    * @param \Drupal\image\ImageStyleStorageInterface $image_style_storage
57    *   The image style entity storage handler.
58    * @param \Drupal\Core\Render\RendererInterface $renderer
59    *   The renderer service.
60    */
61   public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, ImageStyleStorageInterface $image_style_storage, RendererInterface $renderer) {
62     parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings, $current_user, $image_style_storage);
63     $this->renderer = $renderer;
64   }
65
66   /**
67    * {@inheritdoc}
68    */
69   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
70     return new static(
71       $plugin_id,
72       $plugin_definition,
73       $configuration['field_definition'],
74       $configuration['settings'],
75       $configuration['label'],
76       $configuration['view_mode'],
77       $configuration['third_party_settings'],
78       $container->get('current_user'),
79       $container->get('entity_type.manager')->getStorage('image_style'),
80       $container->get('renderer')
81     );
82   }
83
84   /**
85    * {@inheritdoc}
86    *
87    * This has to be overridden because FileFormatterBase expects $item to be
88    * of type \Drupal\file\Plugin\Field\FieldType\FileItem and calls
89    * isDisplayed() which is not in FieldItemInterface.
90    */
91   protected function needsEntityLoad(EntityReferenceItem $item) {
92     return !$item->hasNewEntity();
93   }
94
95   /**
96    * {@inheritdoc}
97    */
98   public function settingsForm(array $form, FormStateInterface $form_state) {
99     $element = parent::settingsForm($form, $form_state);
100
101     $link_types = [
102       'content' => $this->t('Content'),
103       'media' => $this->t('Media entity'),
104     ];
105     $element['image_link']['#options'] = $link_types;
106
107     return $element;
108   }
109
110   /**
111    * {@inheritdoc}
112    */
113   public function settingsSummary() {
114     $summary = parent::settingsSummary();
115
116     $link_types = [
117       'content' => $this->t('Linked to content'),
118       'media' => $this->t('Linked to media item'),
119     ];
120     // Display this setting only if image is linked.
121     $image_link_setting = $this->getSetting('image_link');
122     if (isset($link_types[$image_link_setting])) {
123       $summary[] = $link_types[$image_link_setting];
124     }
125
126     return $summary;
127   }
128
129   /**
130    * {@inheritdoc}
131    */
132   public function viewElements(FieldItemListInterface $items, $langcode) {
133     $elements = [];
134     $media_items = $this->getEntitiesToView($items, $langcode);
135
136     // Early opt-out if the field is empty.
137     if (empty($media_items)) {
138       return $elements;
139     }
140
141     $image_style_setting = $this->getSetting('image_style');
142
143     /** @var \Drupal\media\MediaInterface[] $media_items */
144     foreach ($media_items as $delta => $media) {
145       $elements[$delta] = [
146         '#theme' => 'image_formatter',
147         '#item' => $media->get('thumbnail')->first(),
148         '#item_attributes' => [],
149         '#image_style' => $this->getSetting('image_style'),
150         '#url' => $this->getMediaThumbnailUrl($media, $items->getEntity()),
151       ];
152
153       // Add cacheability of each item in the field.
154       $this->renderer->addCacheableDependency($elements[$delta], $media);
155     }
156
157     // Add cacheability of the image style setting.
158     if ($this->getSetting('image_link') && ($image_style = $this->imageStyleStorage->load($image_style_setting))) {
159       $this->renderer->addCacheableDependency($elements, $image_style);
160     }
161
162     return $elements;
163   }
164
165   /**
166    * {@inheritdoc}
167    */
168   public static function isApplicable(FieldDefinitionInterface $field_definition) {
169     // This formatter is only available for entity types that reference
170     // media items.
171     return ($field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'media');
172   }
173
174   /**
175    * Get the URL for the media thumbnail.
176    *
177    * @param \Drupal\media\MediaInterface $media
178    *   The media item.
179    * @param \Drupal\Core\Entity\EntityInterface $entity
180    *   The entity that the field belongs to.
181    *
182    * @return \Drupal\Core\Url|null
183    *   The URL object for the media item or null if we don't want to add
184    *   a link.
185    */
186   protected function getMediaThumbnailUrl(MediaInterface $media, EntityInterface $entity) {
187     $url = NULL;
188     $image_link_setting = $this->getSetting('image_link');
189     // Check if the formatter involves a link.
190     if ($image_link_setting == 'content') {
191       if (!$entity->isNew()) {
192         $url = $entity->toUrl();
193       }
194     }
195     elseif ($image_link_setting === 'media') {
196       $url = $media->toUrl();
197     }
198     return $url;
199   }
200
201 }