Pull merge.
[yaffs-website] / web / core / modules / file / src / Plugin / views / field / File.php
1 <?php
2
3 namespace Drupal\file\Plugin\views\field;
4
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
7 use Drupal\views\ViewExecutable;
8 use Drupal\views\Plugin\views\display\DisplayPluginBase;
9 use Drupal\views\Plugin\views\field\FieldPluginBase;
10
11 /**
12  * Field handler to provide simple renderer that allows linking to a file.
13  *
14  * @ingroup views_field_handlers
15  *
16  * @ViewsField("file")
17  */
18 class File extends FieldPluginBase {
19
20   /**
21    * {@inheritdoc}
22    */
23   public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
24     parent::init($view, $display, $options);
25
26     if (!empty($options['link_to_file'])) {
27       $this->additional_fields['uri'] = 'uri';
28     }
29   }
30
31   /**
32    * {@inheritdoc}
33    */
34   protected function defineOptions() {
35     $options = parent::defineOptions();
36     $options['link_to_file'] = ['default' => FALSE];
37     return $options;
38   }
39
40   /**
41    * Provide link to file option
42    */
43   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
44     $form['link_to_file'] = [
45       '#title' => $this->t('Link this field to download the file'),
46       '#description' => $this->t("Enable to override this field's links."),
47       '#type' => 'checkbox',
48       '#default_value' => !empty($this->options['link_to_file']),
49     ];
50     parent::buildOptionsForm($form, $form_state);
51   }
52
53   /**
54    * Prepares link to the file.
55    *
56    * @param string $data
57    *   The XSS safe string for the link text.
58    * @param \Drupal\views\ResultRow $values
59    *   The values retrieved from a single row of a view's query result.
60    *
61    * @return string
62    *   Returns a string for the link text.
63    */
64   protected function renderLink($data, ResultRow $values) {
65     if (!empty($this->options['link_to_file']) && $data !== NULL && $data !== '') {
66       $this->options['alter']['make_link'] = TRUE;
67       // @todo Wrap in file_url_transform_relative(). This is currently
68       // impossible. As a work-around, we could add the 'url.site' cache context
69       // to ensure different file URLs are generated for different sites in a
70       // multisite setup, including HTTP and HTTPS versions of the same site.
71       // But unfortunately it's impossible to bubble a cache context here.
72       // Fix in https://www.drupal.org/node/2646744.
73       $this->options['alter']['path'] = file_create_url($this->getValue($values, 'uri'));
74     }
75
76     return $data;
77   }
78
79   /**
80    * {@inheritdoc}
81    */
82   public function render(ResultRow $values) {
83     $value = $this->getValue($values);
84     return $this->renderLink($this->sanitizeValue($value), $values);
85   }
86
87 }