Version 1
[yaffs-website] / web / core / modules / image / src / Plugin / Field / FieldFormatter / ImageUrlFormatter.php
1 <?php
2
3 namespace Drupal\image\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Plugin implementation of the 'image_url' formatter.
11  *
12  * @FieldFormatter(
13  *   id = "image_url",
14  *   label = @Translation("URL to image"),
15  *   field_types = {
16  *     "image"
17  *   }
18  * )
19  */
20 class ImageUrlFormatter extends ImageFormatter {
21
22   /**
23    * {@inheritdoc}
24    */
25   public static function defaultSettings() {
26     return [
27       'image_style' => '',
28     ];
29   }
30
31   /**
32    * {@inheritdoc}
33    */
34   public function settingsForm(array $form, FormStateInterface $form_state) {
35     $element = parent::settingsForm($form, $form_state);
36
37     unset($element['image_link']);;
38
39     return $element;
40   }
41
42   /**
43    * {@inheritdoc}
44    */
45   public function settingsSummary() {
46     $summary = parent::settingsSummary();
47     return [$summary[0]];
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function viewElements(FieldItemListInterface $items, $langcode) {
54     $elements = [];
55
56     /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items */
57     if (empty($images = $this->getEntitiesToView($items, $langcode))) {
58       // Early opt-out if the field is empty.
59       return $elements;
60     }
61
62     /** @var \Drupal\image\ImageStyleInterface $image_style */
63     $image_style = $this->imageStyleStorage->load($this->getSetting('image_style'));
64     /** @var \Drupal\file\FileInterface[] $images */
65     foreach ($images as $delta => $image) {
66       $image_uri = $image->getFileUri();
67       $url = $image_style ? $image_style->buildUrl($image_uri) : file_create_url($image_uri);
68       $url = file_url_transform_relative($url);
69
70       // Add cacheability metadata from the image and image style.
71       $cacheability = CacheableMetadata::createFromObject($image);
72       if ($image_style) {
73         $cacheability->addCacheableDependency(CacheableMetadata::createFromObject($image_style));
74       }
75
76       $elements[$delta] = ['#markup' => $url];
77       $cacheability->applyTo($elements[$delta]);
78     }
79     return $elements;
80   }
81
82 }