1<?php 2 3namespace Drupal\file\Plugin\Field\FieldFormatter; 4 5use Drupal\Core\Field\FieldDefinitionInterface; 6use Drupal\Core\Field\FieldItemInterface; 7use Drupal\Core\Form\FormStateInterface; 8 9/** 10 * Formatter to render a filename as file extension. 11 * 12 * @FieldFormatter( 13 * id = "file_extension", 14 * label = @Translation("File extension"), 15 * field_types = { 16 * "string" 17 * } 18 * ) 19 */ 20class FileExtensionFormatter extends BaseFieldFileFormatterBase { 21 22 /** 23 * {@inheritdoc} 24 */ 25 public static function defaultSettings() { 26 $settings = parent::defaultSettings(); 27 28 $settings['extension_detect_tar'] = FALSE; 29 return $settings; 30 } 31 32 /** 33 * {@inheritdoc} 34 */ 35 public function settingsForm(array $form, FormStateInterface $form_state) { 36 $form = parent::settingsForm($form, $form_state); 37 $form['extension_detect_tar'] = [ 38 '#type' => 'checkbox', 39 '#title' => $this->t('Include tar in extension'), 40 '#description' => $this->t("If the part of the filename just before the extension is '.tar', include this in the extension output."), 41 '#default_value' => $this->getSetting('extension_detect_tar'), 42 ]; 43 return $form; 44 } 45 46 /** 47 * {@inheritdoc} 48 */ 49 protected function viewValue(FieldItemInterface $item) { 50 $filename = $item->value; 51 if (!$this->getSetting('extension_detect_tar')) { 52 return pathinfo($filename, PATHINFO_EXTENSION); 53 } 54 else { 55 $file_parts = explode('.', basename($filename)); 56 if (count($file_parts) > 1) { 57 $extension = array_pop($file_parts); 58 $last_part_in_name = array_pop($file_parts); 59 if ($last_part_in_name === 'tar') { 60 $extension = 'tar.' . $extension; 61 } 62 return $extension; 63 } 64 } 65 } 66 67 /** 68 * {@inheritdoc} 69 */ 70 public static function isApplicable(FieldDefinitionInterface $field_definition) { 71 // Just show this file extension formatter on the filename field. 72 return parent::isApplicable($field_definition) && $field_definition->getName() === 'filename'; 73 } 74 75} 76