Version 1
[yaffs-website] / web / modules / contrib / slick_media / src / Plugin / Field / FieldFormatter / SlickMediaFormatter.php
1 <?php
2
3 namespace Drupal\slick_media\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\slick\SlickDefault;
8 use Drupal\slick\Plugin\Field\FieldFormatter\SlickEntityReferenceFormatterBase;
9 use Drupal\blazy\Dejavu\BlazyVideoTrait;
10
11 /**
12  * Plugin implementation of the 'slick media entity' formatter.
13  *
14  * @FieldFormatter(
15  *   id = "slick_media",
16  *   label = @Translation("Slick Media"),
17  *   description = @Translation("Display the referenced entities as a Slick carousel."),
18  *   field_types = {
19  *     "entity_reference"
20  *   },
21  *   quickedit = {
22  *     "editor" = "disabled"
23  *   }
24  * )
25  */
26 class SlickMediaFormatter extends SlickEntityReferenceFormatterBase {
27
28   use BlazyVideoTrait;
29
30   /**
31    * Returns the blazy manager.
32    */
33   public function blazyManager() {
34     return $this->formatter;
35   }
36
37   /**
38    * {@inheritdoc}
39    */
40   public static function defaultSettings() {
41     return SlickDefault::extendedSettings();
42   }
43
44   /**
45    * {@inheritdoc}
46    */
47   public function viewElements(FieldItemListInterface $items, $langcode) {
48     $entities = $this->getEntitiesToView($items, $langcode);
49
50     // Early opt-out if the field is empty.
51     if (empty($entities)) {
52       return [];
53     }
54
55     // Collects specific settings to this formatter.
56     $settings = $this->getSettings();
57
58     // Asks for Blazy to deal with iFrames, and mobile-optimized lazy loading.
59     $settings['blazy']     = TRUE;
60     $settings['plugin_id'] = $this->getPluginId();
61
62     // Sets dimensions once to reduce method ::transformDimensions() calls.
63     // @todo: A more flexible way to also support paragraphs at one go.
64     if (!empty($settings['image_style']) && ($entities[0]->getEntityTypeId() == 'media')) {
65       $fields = $entities[0]->getFields();
66
67       if (isset($fields['thumbnail'])) {
68         $item = $fields['thumbnail']->get(0);
69
70         $settings['item'] = $item;
71         $settings['uri']  = $item->entity->getFileUri();
72       }
73     }
74
75     $build = ['settings' => $settings];
76
77     $this->formatter->buildSettings($build, $items);
78
79     // Build the elements.
80     $this->buildElements($build, $entities, $langcode);
81
82     return $this->manager()->build($build);
83   }
84
85   /**
86    * {@inheritdoc}
87    */
88   public static function isApplicable(FieldDefinitionInterface $field_definition) {
89     $storage = $field_definition->getFieldStorageDefinition();
90     return $storage->isMultiple() && $storage->getSetting('target_type') === 'media';
91   }
92
93 }