3 namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\Datetime\DateFormatterInterface;
8 use Drupal\Core\Datetime\DrupalDateTime;
9 use Drupal\Core\Field\FieldDefinitionInterface;
10 use Drupal\Core\Field\FieldItemListInterface;
11 use Drupal\Core\Field\FormatterBase;
12 use Drupal\Core\Form\FormStateInterface;
13 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15 use Symfony\Component\HttpFoundation\Request;
18 * Plugin implementation of the 'timestamp' formatter as time ago.
21 * id = "timestamp_ago",
22 * label = @Translation("Time ago"),
30 class TimestampAgoFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
33 * The date formatter service.
35 * @var \Drupal\Core\Datetime\DateFormatterInterface
37 protected $dateFormatter;
40 * The current Request object.
42 * @var \Symfony\Component\HttpFoundation\Request
47 * Constructs a TimestampAgoFormatter object.
49 * @param string $plugin_id
50 * The plugin_id for the formatter.
51 * @param mixed $plugin_definition
52 * The plugin implementation definition.
53 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
54 * The definition of the field to which the formatter is associated.
55 * @param array $settings
56 * The formatter settings.
57 * @param string $label
58 * The formatter label display setting.
59 * @param string $view_mode
61 * @param array $third_party_settings
62 * Any third party settings.
63 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
64 * The date formatter service.
65 * @param \Symfony\Component\HttpFoundation\Request $request
66 * The current request.
68 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatterInterface $date_formatter, Request $request) {
69 parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
71 $this->dateFormatter = $date_formatter;
72 $this->request = $request;
78 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
79 // @see \Drupal\Core\Field\FormatterPluginManager::createInstance().
83 $configuration['field_definition'],
84 $configuration['settings'],
85 $configuration['label'],
86 $configuration['view_mode'],
87 $configuration['third_party_settings'],
88 $container->get('date.formatter'),
89 $container->get('request_stack')->getCurrentRequest()
96 public static function defaultSettings() {
98 'future_format' => '@interval hence',
99 'past_format' => '@interval ago',
101 ] + parent::defaultSettings();
107 public function settingsForm(array $form, FormStateInterface $form_state) {
108 $form = parent::settingsForm($form, $form_state);
110 $form['future_format'] = [
111 '#type' => 'textfield',
112 '#title' => $this->t('Future format'),
113 '#default_value' => $this->getSetting('future_format'),
114 '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
117 $form['past_format'] = [
118 '#type' => 'textfield',
119 '#title' => $this->t('Past format'),
120 '#default_value' => $this->getSetting('past_format'),
121 '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
124 $form['granularity'] = [
126 '#title' => $this->t('Granularity'),
127 '#description' => $this->t('How many time interval units should be shown in the formatted output.'),
128 '#default_value' => $this->getSetting('granularity') ?: 2,
139 public function settingsSummary() {
140 $summary = parent::settingsSummary();
142 $future_date = new DrupalDateTime('1 year 1 month 1 week 1 day 1 hour 1 minute');
143 $past_date = new DrupalDateTime('-1 year -1 month -1 week -1 day -1 hour -1 minute');
144 $granularity = $this->getSetting('granularity');
146 'granularity' => $granularity,
147 'return_as_object' => FALSE,
150 $future_date_interval = new FormattableMarkup($this->getSetting('future_format'), ['@interval' => $this->dateFormatter->formatTimeDiffUntil($future_date->getTimestamp(), $options)]);
151 $past_date_interval = new FormattableMarkup($this->getSetting('past_format'), ['@interval' => $this->dateFormatter->formatTimeDiffSince($past_date->getTimestamp(), $options)]);
153 $summary[] = $this->t('Future date: %display', ['%display' => $future_date_interval]);
154 $summary[] = $this->t('Past date: %display', ['%display' => $past_date_interval]);
162 public function viewElements(FieldItemListInterface $items, $langcode) {
165 foreach ($items as $delta => $item) {
167 $updated = $this->formatTimestamp($item->value);
171 '#markup' => $this->t('never'),
175 $elements[$delta] = $updated;
182 * Formats a timestamp.
184 * @param int $timestamp
185 * A UNIX timestamp to format.
188 * The formatted timestamp string using the past or future format setting.
190 protected function formatTimestamp($timestamp) {
191 $granularity = $this->getSetting('granularity');
193 'granularity' => $granularity,
194 'return_as_object' => TRUE,
197 if ($this->request->server->get('REQUEST_TIME') > $timestamp) {
198 $result = $this->dateFormatter->formatTimeDiffSince($timestamp, $options);
200 '#markup' => new FormattableMarkup($this->getSetting('past_format'), ['@interval' => $result->getString()]),
204 $result = $this->dateFormatter->formatTimeDiffUntil($timestamp, $options);
206 '#markup' => new FormattableMarkup($this->getSetting('future_format'), ['@interval' => $result->getString()]),
209 CacheableMetadata::createFromObject($result)->applyTo($build);