28324aca5cf27d7b482262974e1a676a4bf250ae
[yaffs-website] / web / modules / contrib / blazy / src / Dejavu / BlazyEntityReferenceBase.php
1 <?php
2
3 namespace Drupal\blazy\Dejavu;
4
5 use Drupal\Core\Form\FormStateInterface;
6
7 /**
8  * Base class for entity reference formatters with field details.
9  */
10 abstract class BlazyEntityReferenceBase extends BlazyEntityBase {
11
12   use BlazyEntityTrait;
13
14   /**
15    * {@inheritdoc}
16    */
17   public static function defaultSettings() {
18     return BlazyDefault::extendedSettings();
19   }
20
21   /**
22    * {@inheritdoc}
23    */
24   public function buildElement(array &$build, $entity, $langcode) {
25     $settings = &$build['settings'];
26
27     if (!empty($settings['vanilla'])) {
28       return parent::buildElement($build, $entity, $langcode);
29     }
30
31     $delta     = $settings['delta'];
32     $item_id   = $settings['item_id'];
33     $view_mode = empty($settings['view_mode']) ? 'full' : $settings['view_mode'];
34     $element   = ['settings' => $settings];
35
36     // Built early before stage to allow custom highres video thumbnail later.
37     // Implementor must import: Drupal\blazy\Dejavu\BlazyVideoTrait.
38     $this->getMediaItem($element, $entity);
39
40     // Build the main stage.
41     $this->buildStage($element, $entity, $langcode);
42
43     // If Image rendered is picked, render image as is.
44     if (!empty($settings['image']) && (!empty($settings['media_switch']) && $settings['media_switch'] == 'rendered')) {
45       $element['content'][] = $this->getFieldRenderable($entity, $settings['image'], $view_mode);
46     }
47
48     // Optional image with responsive image, lazyLoad, and lightbox supports.
49     $element[$item_id] = empty($element['item']) ? [] : $this->formatter->getImage($element);
50
51     // Captions if so configured.
52     $this->getCaption($element, $entity, $langcode);
53
54     // Layouts can be builtin, or field, if so configured.
55     if (!empty($settings['layout'])) {
56       $layout = $settings['layout'];
57       if (strpos($layout, 'field_') !== FALSE) {
58         $settings['layout'] = $this->getFieldString($entity, $layout, $langcode);
59       }
60       $element['settings']['layout'] = $settings['layout'];
61     }
62
63     // Classes, if so configured.
64     if (!empty($settings['class'])) {
65       $element['settings']['class'] = $this->getFieldString($entity, $settings['class'], $langcode);
66     }
67
68     // Build the main item.
69     $build['items'][$delta] = $element;
70
71     // Build the thumbnail item.
72     if (!empty($settings['nav'])) {
73       // Thumbnail usages: asNavFor pagers, dot, arrows, photobox thumbnails.
74       $element[$item_id]  = empty($settings['thumbnail_style']) ? [] : $this->formatter->getThumbnail($element['settings']);
75       $element['caption'] = empty($settings['thumbnail_caption']) ? [] : $this->getFieldRenderable($entity, $settings['thumbnail_caption'], $view_mode);
76
77       $build['thumb']['items'][$delta] = $element;
78     }
79   }
80
81   /**
82    * Builds slide captions with possible multi-value fields.
83    */
84   public function getCaption(array &$element, $entity, $langcode) {
85     $settings  = $element['settings'];
86     $view_mode = $settings['view_mode'];
87
88     // Title can be plain text, or link field.
89     if (!empty($settings['title'])) {
90       $field_title = $settings['title'];
91       if (isset($entity->{$field_title})) {
92         if ($entity->hasTranslation($langcode)) {
93           // If the entity has translation, fetch the translated value.
94           $title = $entity->getTranslation($langcode)->get($field_title)->getValue();
95         }
96         else {
97           // Entity doesn't have translation, fetch original value.
98           $title = $entity->get($field_title)->getValue();
99         }
100         if (!empty($title[0]['value']) && !isset($title[0]['uri'])) {
101           // Prevents HTML-filter-enabled text from having bad markups (h2 > p),
102           // except for a few reasonable tags acceptable within H2 tag.
103           $element['caption']['title']['#markup'] = strip_tags($title[0]['value'], '<a><strong><em><span><small>');
104         }
105         elseif (isset($title[0]['uri']) && !empty($title[0]['title'])) {
106           $element['caption']['title'] = $this->getFieldRenderable($entity, $field_title, $view_mode)[0];
107         }
108       }
109     }
110
111     // Other caption fields, if so configured.
112     if (!empty($settings['caption'])) {
113       $caption_items = [];
114       foreach ($settings['caption'] as $i => $field_caption) {
115         if (!isset($entity->{$field_caption})) {
116           continue;
117         }
118         $caption_items[$i] = $this->getFieldRenderable($entity, $field_caption, $view_mode);
119       }
120       if ($caption_items) {
121         $element['caption']['data'] = $caption_items;
122       }
123     }
124
125     // Link, if so configured.
126     if (!empty($settings['link'])) {
127       $field_link = $settings['link'];
128       if (isset($entity->{$field_link})) {
129         $links = $this->getFieldRenderable($entity, $field_link, $view_mode);
130
131         // Only simplify markups for known formatters registered by link.module.
132         if ($links && isset($links['#formatter']) && in_array($links['#formatter'], ['link'])) {
133           $links = [];
134           foreach ($entity->{$field_link} as $i => $link) {
135             $links[$i] = $link->view($view_mode);
136           }
137         }
138         $element['caption']['link'] = $links;
139       }
140     }
141
142     if (!empty($settings['overlay'])) {
143       $element['caption']['overlay'] = $this->getOverlay($settings, $entity, $langcode);
144     }
145   }
146
147   /**
148    * Builds overlay placed within the caption.
149    */
150   public function getOverlay(array $settings, $entity, $langcode) {
151     return $entity->get($settings['overlay'])->view($settings['view_mode']);
152   }
153
154   /**
155    * Build the main background/stage, image or video.
156    *
157    * Main image can be separate image item from video thumbnail for highres.
158    * Fallback to default thumbnail if any, which has no file API.
159    */
160   public function buildStage(array &$element, $entity, $langcode) {
161     $settings = &$element['settings'];
162     $stage    = empty($settings['source_field']) ? '' : $settings['source_field'];
163     $stage    = empty($settings['image']) ? $stage : $settings['image'];
164
165     // The actual video thumbnail has already been downloaded earlier.
166     // This fetches the highres image if provided and available.
167     // With a mix of image and video, image is not always there.
168     if ($stage && isset($entity->{$stage})) {
169       /** @var \Drupal\file\Plugin\Field\FieldType\FileFieldItemList $file */
170       $file = $entity->get($stage);
171       $value = $file->getValue();
172
173       // Do not proceed if it is a Media entity video.
174       if (isset($value[0]) && $value[0]) {
175         // If image, even if multi-value, we can only have one stage per slide.
176         if (isset($value[0]['target_id']) && !empty($value[0]['target_id'])) {
177           if (method_exists($file, 'referencedEntities') && isset($file->referencedEntities()[0])) {
178             /** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $item */
179             $element['item'] = $file->get(0);
180
181             // Collects cache tags to be added for each item in the field.
182             $settings['file_tags'] = $file->referencedEntities()[0]->getCacheTags();
183             $settings['uri'] = $file->referencedEntities()[0]->getFileUri();
184           }
185         }
186         // If a VEF with a text, or link field.
187         elseif (isset($value[0]['value']) || isset($value[0]['uri'])) {
188           $external_url = $this->getFieldString($entity, $stage, $langcode);
189
190           if ($external_url) {
191             $this->buildVideo($settings, $external_url);
192             $element['item'] = $value;
193           }
194         }
195       }
196     }
197   }
198
199   /**
200    * {@inheritdoc}
201    */
202   public function settingsForm(array $form, FormStateInterface $form_state) {
203     $element = parent::settingsForm($form, $form_state);
204
205     if (isset($element['layout'])) {
206       $layout_description = $element['layout']['#description'];
207       $element['layout']['#description'] = $this->t('Create a dedicated List (text - max number 1) field related to the caption placement to have unique layout per slide with the following supported keys: top, right, bottom, left, center, center-top, etc. Be sure its formatter is Key.') . ' ' . $layout_description;
208     }
209
210     if (isset($element['media_switch'])) {
211       $element['media_switch']['#options']['rendered'] = $this->t('Image rendered by its formatter');
212       $element['media_switch']['#description'] .= ' ' . $this->t('Be sure the enabled fields here are not hidden/disabled at its view mode.');
213     }
214
215     if (isset($element['caption'])) {
216       $element['caption']['#description'] = $this->t('Check fields to be treated as captions, even if not caption texts.');
217     }
218
219     if (isset($element['image']['#description'])) {
220       $element['image']['#description'] .= ' ' . $this->t('For video, this allows separate highres image, be sure the same field used for Image to have a mix of videos and images. Leave empty to fallback to the video provider thumbnails. The formatter/renderer is managed by <strong>@namespace</strong> formatter. Meaning original formatter ignored. If you want original formatters, check <strong>Vanilla</strong> option. Alternatively choose <strong>Media switcher &gt; Image rendered </strong>, other image-related settings here will be ignored. <strong>Supported fields</strong>: Image, Video Embed Field.', ['@namespace' => $this->getPluginId()]);
221     }
222
223     if (isset($element['overlay']['#description'])) {
224       $element['overlay']['#description'] .= ' ' . $this->t('The formatter/renderer is managed by the child formatter. <strong>Supported fields</strong>: Image, Video Embed Field, Media Entity.');
225     }
226
227     return $element;
228   }
229
230   /**
231    * {@inheritdoc}
232    */
233   public function getScopedFormElements() {
234     $admin       = $this->admin();
235     $target_type = $this->getFieldSetting('target_type');
236     $views_ui    = $this->getFieldSetting('handler') == 'default';
237     $bundles     = $views_ui ? [] : $this->getFieldSetting('handler_settings')['target_bundles'];
238     $strings     = ['text', 'string', 'list_string'];
239     $strings     = $admin->getFieldOptions($bundles, $strings, $target_type);
240     $texts       = ['text', 'text_long', 'string', 'string_long', 'link'];
241     $texts       = $admin->getFieldOptions($bundles, $texts, $target_type);
242     $links       = ['text', 'string', 'link'];
243
244     return [
245       'background'        => TRUE,
246       'box_captions'      => TRUE,
247       'breakpoints'       => BlazyDefault::getConstantBreakpoints(),
248       'captions'          => $admin->getFieldOptions($bundles, [], $target_type),
249       'classes'           => $strings,
250       'fieldable_form'    => TRUE,
251       'images'            => $admin->getFieldOptions($bundles, ['image'], $target_type),
252       'image_style_form'  => TRUE,
253       'layouts'           => $strings,
254       'links'             => $admin->getFieldOptions($bundles, $links, $target_type),
255       'media_switch_form' => TRUE,
256       'multimedia'        => TRUE,
257       'thumb_captions'    => $texts,
258       'thumb_positions'   => TRUE,
259       'nav'               => TRUE,
260       'titles'            => $texts,
261       'vanilla'           => TRUE,
262     ] + parent::getScopedFormElements();
263   }
264
265 }