TimestampAgoFormatter.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. <?php
  2. namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
  3. use Drupal\Component\Render\FormattableMarkup;
  4. use Drupal\Core\Cache\CacheableMetadata;
  5. use Drupal\Core\Datetime\DateFormatterInterface;
  6. use Drupal\Core\Datetime\DrupalDateTime;
  7. use Drupal\Core\Field\FieldDefinitionInterface;
  8. use Drupal\Core\Field\FieldItemListInterface;
  9. use Drupal\Core\Field\FormatterBase;
  10. use Drupal\Core\Form\FormStateInterface;
  11. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. /**
  15. * Plugin implementation of the 'timestamp' formatter as time ago.
  16. *
  17. * @FieldFormatter(
  18. * id = "timestamp_ago",
  19. * label = @Translation("Time ago"),
  20. * field_types = {
  21. * "timestamp",
  22. * "created",
  23. * "changed",
  24. * }
  25. * )
  26. */
  27. class TimestampAgoFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
  28. /**
  29. * The date formatter service.
  30. *
  31. * @var \Drupal\Core\Datetime\DateFormatterInterface
  32. */
  33. protected $dateFormatter;
  34. /**
  35. * The current Request object.
  36. *
  37. * @var \Symfony\Component\HttpFoundation\Request
  38. */
  39. protected $request;
  40. /**
  41. * Constructs a TimestampAgoFormatter object.
  42. *
  43. * @param string $plugin_id
  44. * The plugin_id for the formatter.
  45. * @param mixed $plugin_definition
  46. * The plugin implementation definition.
  47. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  48. * The definition of the field to which the formatter is associated.
  49. * @param array $settings
  50. * The formatter settings.
  51. * @param string $label
  52. * The formatter label display setting.
  53. * @param string $view_mode
  54. * The view mode.
  55. * @param array $third_party_settings
  56. * Any third party settings.
  57. * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
  58. * The date formatter service.
  59. * @param \Symfony\Component\HttpFoundation\Request $request
  60. * The current request.
  61. */
  62. public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatterInterface $date_formatter, Request $request) {
  63. parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
  64. $this->dateFormatter = $date_formatter;
  65. $this->request = $request;
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  71. // @see \Drupal\Core\Field\FormatterPluginManager::createInstance().
  72. return new static(
  73. $plugin_id,
  74. $plugin_definition,
  75. $configuration['field_definition'],
  76. $configuration['settings'],
  77. $configuration['label'],
  78. $configuration['view_mode'],
  79. $configuration['third_party_settings'],
  80. $container->get('date.formatter'),
  81. $container->get('request_stack')->getCurrentRequest()
  82. );
  83. }
  84. /**
  85. * {@inheritdoc}
  86. */
  87. public static function defaultSettings() {
  88. return [
  89. 'future_format' => '@interval hence',
  90. 'past_format' => '@interval ago',
  91. 'granularity' => 2,
  92. ] + parent::defaultSettings();
  93. }
  94. /**
  95. * {@inheritdoc}
  96. */
  97. public function settingsForm(array $form, FormStateInterface $form_state) {
  98. $form = parent::settingsForm($form, $form_state);
  99. $form['future_format'] = [
  100. '#type' => 'textfield',
  101. '#title' => $this->t('Future format'),
  102. '#default_value' => $this->getSetting('future_format'),
  103. '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
  104. ];
  105. $form['past_format'] = [
  106. '#type' => 'textfield',
  107. '#title' => $this->t('Past format'),
  108. '#default_value' => $this->getSetting('past_format'),
  109. '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
  110. ];
  111. $form['granularity'] = [
  112. '#type' => 'number',
  113. '#title' => $this->t('Granularity'),
  114. '#description' => $this->t('How many time interval units should be shown in the formatted output.'),
  115. '#default_value' => $this->getSetting('granularity') ?: 2,
  116. '#min' => 1,
  117. '#max' => 6,
  118. ];
  119. return $form;
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. public function settingsSummary() {
  125. $summary = parent::settingsSummary();
  126. $future_date = new DrupalDateTime('1 year 1 month 1 week 1 day 1 hour 1 minute');
  127. $past_date = new DrupalDateTime('-1 year -1 month -1 week -1 day -1 hour -1 minute');
  128. $granularity = $this->getSetting('granularity');
  129. $options = [
  130. 'granularity' => $granularity,
  131. 'return_as_object' => FALSE,
  132. ];
  133. $future_date_interval = new FormattableMarkup($this->getSetting('future_format'), ['@interval' => $this->dateFormatter->formatTimeDiffUntil($future_date->getTimestamp(), $options)]);
  134. $past_date_interval = new FormattableMarkup($this->getSetting('past_format'), ['@interval' => $this->dateFormatter->formatTimeDiffSince($past_date->getTimestamp(), $options)]);
  135. $summary[] = $this->t('Future date: %display', ['%display' => $future_date_interval]);
  136. $summary[] = $this->t('Past date: %display', ['%display' => $past_date_interval]);
  137. return $summary;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. public function viewElements(FieldItemListInterface $items, $langcode) {
  143. $elements = [];
  144. foreach ($items as $delta => $item) {
  145. if ($item->value) {
  146. $updated = $this->formatTimestamp($item->value);
  147. }
  148. else {
  149. $updated = [
  150. '#markup' => $this->t('never'),
  151. ];
  152. }
  153. $elements[$delta] = $updated;
  154. }
  155. return $elements;
  156. }
  157. /**
  158. * Formats a timestamp.
  159. *
  160. * @param int $timestamp
  161. * A UNIX timestamp to format.
  162. *
  163. * @return array
  164. * The formatted timestamp string using the past or future format setting.
  165. */
  166. protected function formatTimestamp($timestamp) {
  167. $granularity = $this->getSetting('granularity');
  168. $options = [
  169. 'granularity' => $granularity,
  170. 'return_as_object' => TRUE,
  171. ];
  172. if ($this->request->server->get('REQUEST_TIME') > $timestamp) {
  173. $result = $this->dateFormatter->formatTimeDiffSince($timestamp, $options);
  174. $build = [
  175. '#markup' => new FormattableMarkup($this->getSetting('past_format'), ['@interval' => $result->getString()]),
  176. ];
  177. }
  178. else {
  179. $result = $this->dateFormatter->formatTimeDiffUntil($timestamp, $options);
  180. $build = [
  181. '#markup' => new FormattableMarkup($this->getSetting('future_format'), ['@interval' => $result->getString()]),
  182. ];
  183. }
  184. CacheableMetadata::createFromObject($result)->applyTo($build);
  185. return $build;
  186. }
  187. }