0facb7e033885818c8f96921c09f012b9618f0e3
[yaffs-website] / web / core / modules / file / src / Plugin / Field / FieldFormatter / FileUriFormatter.php
1 <?php
2
3 namespace Drupal\file\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemInterface;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Formatter to render the file URI to its download path.
11  *
12  * @FieldFormatter(
13  *   id = "file_uri",
14  *   label = @Translation("File URI"),
15  *   field_types = {
16  *     "uri",
17  *     "file_uri",
18  *   }
19  * )
20  */
21 class FileUriFormatter extends BaseFieldFileFormatterBase {
22
23   /**
24    * {@inheritdoc}
25    */
26   public static function defaultSettings() {
27     $settings = parent::defaultSettings();
28
29     $settings['file_download_path'] = FALSE;
30     return $settings;
31   }
32
33   /**
34    * {@inheritdoc}
35    */
36   public function settingsForm(array $form, FormStateInterface $form_state) {
37     $form = parent::settingsForm($form, $form_state);
38
39     $form['file_download_path'] = [
40       '#title' => $this->t('Display the file download URI'),
41       '#type' => 'checkbox',
42       '#default_value' => $this->getSetting('file_download_path'),
43     ];
44
45     return $form;
46   }
47
48   /**
49    * {@inheritdoc}
50    */
51   protected function viewValue(FieldItemInterface $item) {
52     $value = $item->value;
53     if ($this->getSetting('file_download_path')) {
54       // @todo Wrap in file_url_transform_relative(). This is currently
55       // impossible. See BaseFieldFileFormatterBase::viewElements(). Fix in
56       // https://www.drupal.org/node/2646744.
57       $value = file_create_url($value);
58     }
59     return $value;
60   }
61
62   /**
63    * {@inheritdoc}
64    */
65   public static function isApplicable(FieldDefinitionInterface $field_definition) {
66     return parent::isApplicable($field_definition) && $field_definition->getName() === 'uri';
67   }
68
69 }