TimestampFormatter.php 6.14 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;

5
use Drupal\Core\Datetime\DateFormatterInterface;
6 7
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
8
use Drupal\Core\Field\FieldItemListInterface;
9 10 11 12
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
13 14 15 16 17 18 19 20 21 22

/**
 * Plugin implementation of the 'timestamp' formatter.
 *
 * @FieldFormatter(
 *   id = "timestamp",
 *   label = @Translation("Default"),
 *   field_types = {
 *     "timestamp",
 *     "created",
23
 *     "changed",
24 25 26
 *   }
 * )
 */
27 28 29 30 31
class TimestampFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

  /**
   * The date formatter service.
   *
32
   * @var \Drupal\Core\Datetime\DateFormatterInterface
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
   */
  protected $dateFormatter;

  /**
   * The date format entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $dateFormatStorage;

  /**
   * Constructs a new TimestampFormatter.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Third party settings.
60
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
61 62 63 64
   *   The date formatter service.
   * @param \Drupal\Core\Entity\EntityStorageInterface $date_format_storage
   *   The date format storage.
   */
65
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatterInterface $date_formatter, EntityStorageInterface $date_format_storage) {
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);

    $this->dateFormatter = $date_formatter;
    $this->dateFormatStorage = $date_format_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('date.formatter'),
85
      $container->get('entity_type.manager')->getStorage('date_format')
86 87 88 89 90 91 92
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
93
    return [
94 95 96
      'date_format' => 'medium',
      'custom_date_format' => '',
      'timezone' => '',
97
    ] + parent::defaultSettings();
98 99 100 101 102 103 104 105
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements = parent::settingsForm($form, $form_state);

106
    $date_formats = [];
107 108

    foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) {
109
      $date_formats[$machine_name] = $this->t('@name format: @date', ['@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name)]);
110 111 112 113
    }

    $date_formats['custom'] = $this->t('Custom');

114
    $elements['date_format'] = [
115 116 117 118
      '#type' => 'select',
      '#title' => $this->t('Date format'),
      '#options' => $date_formats,
      '#default_value' => $this->getSetting('date_format') ?: 'medium',
119
    ];
120

121
    $elements['custom_date_format'] = [
122 123
      '#type' => 'textfield',
      '#title' => $this->t('Custom date format'),
124
      '#description' => $this->t('See <a href="http://php.net/manual/function.date.php" target="_blank">the documentation for PHP date formats</a>.'),
125
      '#default_value' => $this->getSetting('custom_date_format') ?: '',
126
    ];
127

128 129 130
    $elements['custom_date_format']['#states']['visible'][] = [
      ':input[name="fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings][date_format]"]' => ['value' => 'custom'],
    ];
131

132
    $elements['timezone'] = [
133 134
      '#type' => 'select',
      '#title' => $this->t('Time zone'),
135
      '#options' => ['' => $this->t('- Default site/user time zone -')] + system_time_zones(FALSE, TRUE),
136
      '#default_value' => $this->getSetting('timezone'),
137
    ];
138 139 140 141 142 143 144 145 146 147 148

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = parent::settingsSummary();

    $date_format = $this->getSetting('date_format');
149
    $summary[] = $this->t('Date format: @date_format', ['@date_format' => $date_format]);
150
    if ($this->getSetting('date_format') === 'custom' && ($custom_date_format = $this->getSetting('custom_date_format'))) {
151
      $summary[] = $this->t('Custom date format: @custom_date_format', ['@custom_date_format' => $custom_date_format]);
152 153
    }
    if ($timezone = $this->getSetting('timezone')) {
154
      $summary[] = $this->t('Time zone: @timezone', ['@timezone' => $timezone]);
155 156 157 158
    }

    return $summary;
  }
159 160 161 162

  /**
   * {@inheritdoc}
   */
163
  public function viewElements(FieldItemListInterface $items, $langcode) {
164
    $elements = [];
165

166 167 168 169 170 171 172 173 174 175 176
    $date_format = $this->getSetting('date_format');
    $custom_date_format = '';
    $timezone = $this->getSetting('timezone') ?: NULL;
    $langcode = NULL;

    // If an RFC2822 date format is requested, then the month and day have to
    // be in English. @see http://www.faqs.org/rfcs/rfc2822.html
    if ($date_format === 'custom' && ($custom_date_format = $this->getSetting('custom_date_format')) === 'r') {
      $langcode = 'en';
    }

177
    foreach ($items as $delta => $item) {
178 179 180 181 182 183
      $elements[$delta] = [
        '#cache' => [
          'contexts' => [
            'timezone',
          ],
        ],
184
        '#markup' => $this->dateFormatter->format($item->value, $date_format, $custom_date_format, $timezone, $langcode),
185
      ];
186 187 188 189 190 191
    }

    return $elements;
  }

}