From bc7d537553a17ac52797784a73d887bcbc2bbe15 Mon Sep 17 00:00:00 2001
From: legolasbo <postbuschris@hotmail.com>
Date: Sat, 17 Jan 2015 12:03:47 +0100
Subject: [PATCH] Straight port of views' TimeAgo formatter

---
 .../FieldFormatter/DateTimeTimeAgoFormatter.php    | 182 +++++++++++++++++++++
 1 file changed, 182 insertions(+)
 create mode 100644 core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php

diff --git a/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php
new file mode 100644
index 0000000..5b337ab
--- /dev/null
+++ b/core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php
@@ -0,0 +1,182 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\datetime\Plugin\Field\FieldFormatter\DateTimePlainFormatter.
+ */
+
+namespace Drupal\datetime\Plugin\Field\FieldFormatter;
+
+use Drupal\Core\Datetime\DateFormatter;
+use Drupal\Core\Datetime\DrupalDateTime;
+use Drupal\Core\Field\FieldDefinitionInterface;
+use Drupal\Core\Field\FieldItemListInterface;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Field\FormatterBase;
+use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+
+/**
+ * Plugin implementation of the 'datetime_plain' formatter.
+ *
+ * @FieldFormatter(
+ *   id = "datetime_time_ago",
+ *   label = @Translation("Time ago"),
+ *   field_types = {
+ *     "datetime"
+ *   }
+ *)
+ */
+class DateTimeTimeAgoFormatter extends FormatterBase implements ContainerFactoryPluginInterface{
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function defaultSettings() {
+    return array(
+      'format_type' => 'time span',
+      'granularity' => 2,
+    ) + parent::defaultSettings();
+  }
+
+  /**
+   * The date formatter service.
+   *
+   * @var \Drupal\Core\Datetime\DateFormatter
+   */
+  protected $dateFormatter;
+
+  /**
+   * Constructs a DateTimeTimeAgoFormatter object.
+   *
+   * @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.
+   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
+   *   The date formatter service.
+   */
+  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, DateFormatter $date_formatter) {
+    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
+
+    $this->dateFormatter = $date_formatter;
+  }
+
+  /**
+   * {@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')
+    );
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function viewElements(FieldItemListInterface $items) {
+
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+
+      $output = '';
+      if (!empty($item->date)) {
+        // The date was created and verified during field_load(), so it is safe
+        // to use without further inspection.
+        $output = $this->dateFormat($item->date);
+      }
+      $elements[$delta] = array('#markup' => $output);
+    }
+
+    return $elements;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function settingsForm(array $form, FormStateInterface $form_state) {
+    $elements['format_type'] = array(
+      '#type' => 'select',
+      '#title' => $this->t('Date format'),
+      '#options' => array(
+        'raw time ago' => $this->t('Time ago'),
+        'time ago' => $this->t('Time ago (with "ago" appended)'),
+        'raw time hence' => $this->t('Time hence'),
+        'time hence' => $this->t('Time hence (with "hence" appended)'),
+        'raw time span' => $this->t('Time span (future dates have "-" prepended)'),
+        'inverse time span' => $this->t('Time span (past dates have "-" prepended)'),
+        'time span' => $this->t('Time span (with "ago/hence" appended)'),
+      ),
+      '#default_value' => $this->getSetting('format_type'),
+    );
+
+    $elements['granularity'] = array(
+      '#type' => 'number',
+      '#title' => 'Granularity',
+      '#default_value' => $this->getSetting('granularity'),
+    );
+
+    return $elements;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function settingsSummary() {
+    $summary = array();
+    $future_date = new DrupalDateTime(time() + 1234);
+    $past_date = new DrupalDateTime(time() - 1234);
+    $summary[] = t('Future date: !display', array('!display' => $this->dateFormat($future_date, FALSE)));
+    $summary[] = t('Past date: !display', array('!display' => $this->dateFormat($past_date, FALSE)));
+    return $summary;
+  }
+
+  /**
+   * Creates a formatted date value as a string.
+   *
+   * @param object $date
+   *   A date object.
+   *
+   * @return string
+   *   A formatted date string using the chosen format.
+   */
+  function dateFormat($date) {
+    $format = $this->getSetting('format_type');
+    $granularity = $this->getSetting('granularity');
+    $interval = REQUEST_TIME - $date->getTimestamp();
+    switch ($format) {
+      case 'time ago':
+        return $this->t('%time ago', array('%time' => $this->dateFormatter->formatInterval($interval, $granularity)));
+      case 'raw time hence':
+        return $this->dateFormatter->formatInterval(-$interval, $granularity);
+      case 'time hence':
+        return $this->t('%time hence', array('%time' => $this->dateFormatter->formatInterval(-$interval, $granularity)));
+      case 'raw time span':
+        return ($interval < 0 ? '-' : '') . $this->dateFormatter->formatInterval(abs($interval), $granularity);
+      case 'inverse time span':
+        return ($interval > 0 ? '-' : '') . $this->dateFormatter->formatInterval(abs($interval), $granularity);
+      case 'time span':
+        return $this->t(($interval < 0 ? '%time hence' : '%time ago'), array('%time' => $this->dateFormatter->formatInterval(abs($interval), $granularity)));
+      default: // Fallback to raw time ago.
+        return $this->dateFormatter->formatInterval($interval, $granularity);
+    }
+  }
+}
\ No newline at end of file
-- 
1.8.4.2

