Extension.php 1.72 KB
Newer Older
1
2
3
4
5
6
7
<?php

/**
 * @file
 * Definition of views_handler_field_file_extension.
 */

8
namespace Drupal\file\Plugin\views\field;
dawehner's avatar
dawehner committed
9

10
use Drupal\Component\Annotation\PluginID;
dawehner's avatar
dawehner committed
11
12
use Drupal\views\Plugin\views\field\FieldPluginBase;

13
14
/**
 * Returns a pure file extension of the file, for example 'module'.
dawehner's avatar
dawehner committed
15
 *
16
 * @ingroup views_field_handlers
17
 *
18
 * @PluginID("file_extension")
dawehner's avatar
dawehner committed
19
20
 */
class Extension extends FieldPluginBase {
21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['extension_detect_tar'] = array('default' => FALSE, 'bool' => TRUE);
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, &$form_state) {
    parent::buildOptionsForm($form, $form_state);
    $form['extension_detect_tar'] = array(
      '#type' => 'checkbox',
      '#title' => t('Detect if tar is part of the extension'),
      '#description' => t("See if the previous extension is '.tar' and if so, add that, so we see 'tar.gz' or 'tar.bz2' instead of just 'gz'."),
40
      '#default_value' => $this->options['extension_detect_tar'],
41
42
43
    );
  }

44
  function render($values) {
45
    $value = $this->getValue($values);
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
    if (!$this->options['extension_detect_tar']) {
      if (preg_match('/\.([^\.]+)$/', $value, $match)) {
        return $this->sanitizeValue($match[1]);
      }
    }
    else {
      $file_parts = explode('.', basename($value));
      // If there is an extension.
      if (count($file_parts) > 1) {
        $extension = array_pop($file_parts);
        $last_part_in_name = array_pop($file_parts);
        if ($last_part_in_name === 'tar') {
          $extension = 'tar.' . $extension;
        }
        return $this->sanitizeValue($extension);
      }
62
63
    }
  }
64

65
}