Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Field / Plugin / Field / FieldFormatter / TimestampAgoFormatter.php
1 <?php
2
3 namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
4
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;
15
16 /**
17  * Plugin implementation of the 'timestamp' formatter as time ago.
18  *
19  * @FieldFormatter(
20  *   id = "timestamp_ago",
21  *   label = @Translation("Time ago"),
22  *   field_types = {
23  *     "timestamp",
24  *     "created",
25  *     "changed",
26  *   }
27  * )
28  */
29 class TimestampAgoFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
30
31   /**
32    * The date formatter service.
33    *
34    * @var \Drupal\Core\Datetime\DateFormatterInterface
35    */
36   protected $dateFormatter;
37
38   /**
39    * The current Request object.
40    *
41    * @var \Symfony\Component\HttpFoundation\Request
42    */
43   protected $request;
44
45   /**
46    * Constructs a TimestampAgoFormatter object.
47    *
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
59    *   The 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.
66    */
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);
69
70     $this->dateFormatter = $date_formatter;
71     $this->request = $request;
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
78     // @see \Drupal\Core\Field\FormatterPluginManager::createInstance().
79     return new static(
80       $plugin_id,
81       $plugin_definition,
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()
89     );
90   }
91
92   /**
93    * {@inheritdoc}
94    */
95   public static function defaultSettings() {
96     return [
97       'future_format' => '@interval hence',
98       'past_format' => '@interval ago',
99       'granularity' => 2,
100     ] + parent::defaultSettings();
101   }
102
103   /**
104    * {@inheritdoc}
105    */
106   public function settingsForm(array $form, FormStateInterface $form_state) {
107     $elements = parent::settingsForm($form, $form_state);
108
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.'),
114     ];
115
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.'),
121     ];
122
123     $elements['granularity'] = [
124       '#type' => 'number',
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,
128       '#min' => 1,
129       '#max' => 6,
130     ];
131
132     return $elements;
133   }
134
135   /**
136    * {@inheritdoc}
137    */
138   public function settingsSummary() {
139     $summary = parent::settingsSummary();
140
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)]);
145
146     return $summary;
147   }
148
149   /**
150    * {@inheritdoc}
151    */
152   public function viewElements(FieldItemListInterface $items, $langcode) {
153     $elements = [];
154
155     foreach ($items as $delta => $item) {
156       if ($item->value) {
157         $updated = $this->formatTimestamp($item->value);
158       }
159       else {
160         $updated = [
161           '#markup' => $this->t('never'),
162         ];
163       }
164
165       $elements[$delta] = $updated;
166     }
167
168     return $elements;
169   }
170
171   /**
172    * Formats a timestamp.
173    *
174    * @param int $timestamp
175    *   A UNIX timestamp to format.
176    *
177    * @return array
178    *   The formatted timestamp string using the past or future format setting.
179    */
180   protected function formatTimestamp($timestamp) {
181     $granularity = $this->getSetting('granularity');
182     $options = [
183       'granularity' => $granularity,
184       'return_as_object' => TRUE,
185     ];
186
187     if ($this->request->server->get('REQUEST_TIME') > $timestamp) {
188       $result = $this->dateFormatter->formatTimeDiffSince($timestamp, $options);
189       $build = [
190         '#markup' => SafeMarkup::format($this->getSetting('past_format'), ['@interval' => $result->getString()]),
191       ];
192     }
193     else {
194       $result = $this->dateFormatter->formatTimeDiffUntil($timestamp, $options);
195       $build = [
196         '#markup' => SafeMarkup::format($this->getSetting('future_format'), ['@interval' => $result->getString()]),
197       ];
198     }
199     CacheableMetadata::createFromObject($result)->applyTo($build);
200     return $build;
201   }
202
203 }