3 namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
5 use Drupal\Component\Utility\SafeMarkup;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\Datetime\DateFormatterInterface;
8 use Drupal\Core\Field\FieldDefinitionInterface;
9 use Drupal\Core\Field\FieldItemListInterface;
10 use Drupal\Core\Field\FormatterBase;
11 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14 use Symfony\Component\HttpFoundation\Request;
17 * Plugin implementation of the 'timestamp' formatter as time ago.
20 * id = "timestamp_ago",
21 * label = @Translation("Time ago"),
29 class TimestampAgoFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
32 * The date formatter service.
34 * @var \Drupal\Core\Datetime\DateFormatterInterface
36 protected $dateFormatter;
39 * The current Request object.
41 * @var \Symfony\Component\HttpFoundation\Request
46 * Constructs a TimestampAgoFormatter object.
48 * @param string $plugin_id
49 * The plugin_id for the formatter.
50 * @param mixed $plugin_definition
51 * The plugin implementation definition.
52 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
53 * The definition of the field to which the formatter is associated.
54 * @param array $settings
55 * The formatter settings.
56 * @param string $label
57 * The formatter label display setting.
58 * @param string $view_mode
60 * @param array $third_party_settings
61 * Any third party settings.
62 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
63 * The date formatter service.
64 * @param \Symfony\Component\HttpFoundation\Request $request
65 * The current request.
67 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatterInterface $date_formatter, Request $request) {
68 parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
70 $this->dateFormatter = $date_formatter;
71 $this->request = $request;
77 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
78 // @see \Drupal\Core\Field\FormatterPluginManager::createInstance().
82 $configuration['field_definition'],
83 $configuration['settings'],
84 $configuration['label'],
85 $configuration['view_mode'],
86 $configuration['third_party_settings'],
87 $container->get('date.formatter'),
88 $container->get('request_stack')->getCurrentRequest()
95 public static function defaultSettings() {
97 'future_format' => '@interval hence',
98 'past_format' => '@interval ago',
100 ] + parent::defaultSettings();
106 public function settingsForm(array $form, FormStateInterface $form_state) {
107 $elements = parent::settingsForm($form, $form_state);
109 $form['future_format'] = [
110 '#type' => 'textfield',
111 '#title' => $this->t('Future format'),
112 '#default_value' => $this->getSetting('future_format'),
113 '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
116 $form['past_format'] = [
117 '#type' => 'textfield',
118 '#title' => $this->t('Past format'),
119 '#default_value' => $this->getSetting('past_format'),
120 '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
123 $elements['granularity'] = [
125 '#title' => $this->t('Granularity'),
126 '#description' => $this->t('How many time interval units should be shown in the formatted output.'),
127 '#default_value' => $this->getSetting('granularity') ?: 2,
138 public function settingsSummary() {
139 $summary = parent::settingsSummary();
141 $future_date = strtotime('1 year 1 month 1 week 1 day 1 hour 1 minute');
142 $past_date = strtotime('-1 year -1 month -1 week -1 day -1 hour -1 minute');
143 $summary[] = $this->t('Future date: %display', ['%display' => $this->formatTimestamp($future_date)]);
144 $summary[] = $this->t('Past date: %display', ['%display' => $this->formatTimestamp($past_date)]);
152 public function viewElements(FieldItemListInterface $items, $langcode) {
155 foreach ($items as $delta => $item) {
157 $updated = $this->formatTimestamp($item->value);
161 '#markup' => $this->t('never'),
165 $elements[$delta] = $updated;
172 * Formats a timestamp.
174 * @param int $timestamp
175 * A UNIX timestamp to format.
178 * The formatted timestamp string using the past or future format setting.
180 protected function formatTimestamp($timestamp) {
181 $granularity = $this->getSetting('granularity');
183 'granularity' => $granularity,
184 'return_as_object' => TRUE,
187 if ($this->request->server->get('REQUEST_TIME') > $timestamp) {
188 $result = $this->dateFormatter->formatTimeDiffSince($timestamp, $options);
190 '#markup' => SafeMarkup::format($this->getSetting('past_format'), ['@interval' => $result->getString()]),
194 $result = $this->dateFormatter->formatTimeDiffUntil($timestamp, $options);
196 '#markup' => SafeMarkup::format($this->getSetting('future_format'), ['@interval' => $result->getString()]),
199 CacheableMetadata::createFromObject($result)->applyTo($build);