Date.php 6.76 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\views\Plugin\views\field\Date.
merlinofchaos's avatar
merlinofchaos committed
6 7
 */

8
namespace Drupal\views\Plugin\views\field;
9

10
use Drupal\Core\Entity\EntityStorageInterface;
11
use Drupal\views\ResultRow;
12 13
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Datetime\Date as DateService;
dawehner's avatar
dawehner committed
14

merlinofchaos's avatar
merlinofchaos committed
15 16 17 18
/**
 * A handler to provide proper displays for dates.
 *
 * @ingroup views_field_handlers
19
 *
20
 * @ViewsField("date")
dawehner's avatar
dawehner committed
21
 */
22
class Date extends FieldPluginBase {
23

24 25 26 27 28 29 30 31 32 33
  /**
   * The date service.
   *
   * @var \Drupal\Core\Datetime\Date
   */
  protected $dateService;

  /**
   * The date format storage.
   *
34
   * @var \Drupal\Core\Entity\EntityStorageInterface
35 36 37 38 39 40 41 42 43 44
   */
  protected $dateFormatStorage;

  /**
   * Constructs a new Date object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
45
   * @param mixed $plugin_definition
46 47 48
   *   The plugin implementation definition.
   * @param \Drupal\Core\Datetime\Date $date_service
   *   The date service.
49
   * @param \Drupal\Core\Entity\EntityStorageInterface $date_format_storage
50 51
   *   The date format storage.
   */
52
  public function __construct(array $configuration, $plugin_id, $plugin_definition, DateService $date_service, EntityStorageInterface $date_format_storage) {
53 54 55 56 57 58 59 60 61
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->dateService = $date_service;
    $this->dateFormatStorage = $date_format_storage;
  }

  /**
   * {@inheritdoc}
   */
62
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
63 64 65 66 67
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('date'),
68
      $container->get('entity.manager')->getStorage('date_format')
69 70 71
    );
  }

72 73
  protected function defineOptions() {
    $options = parent::defineOptions();
merlinofchaos's avatar
merlinofchaos committed
74 75 76

    $options['date_format'] = array('default' => 'small');
    $options['custom_date_format'] = array('default' => '');
77
    $options['timezone'] = array('default' => '');
merlinofchaos's avatar
merlinofchaos committed
78 79 80 81

    return $options;
  }

82
  public function buildOptionsForm(&$form, &$form_state) {
merlinofchaos's avatar
merlinofchaos committed
83 84

    $date_formats = array();
85 86
    foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) {
      $date_formats[$machine_name] = t('@name format: @date', array('@name' => $value->label(), '@date' => $this->dateService->format(REQUEST_TIME, $machine_name)));
merlinofchaos's avatar
merlinofchaos committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    }

    $form['date_format'] = array(
      '#type' => 'select',
      '#title' => t('Date format'),
      '#options' => $date_formats + array(
        'custom' => t('Custom'),
        'raw time ago' => t('Time ago'),
        'time ago' => t('Time ago (with "ago" appended)'),
        'raw time hence' => t('Time hence'),
        'time hence' => t('Time hence (with "hence" appended)'),
        'raw time span' => t('Time span (future dates have "-" prepended)'),
        'inverse time span' => t('Time span (past dates have "-" prepended)'),
        'time span' => t('Time span (with "ago/hence" appended)'),
      ),
      '#default_value' => isset($this->options['date_format']) ? $this->options['date_format'] : 'small',
    );
    $form['custom_date_format'] = array(
      '#type' => 'textfield',
      '#title' => t('Custom date format'),
107
      '#description' => t('If "Custom", see <a href="http://us.php.net/manual/en/function.date.php" target="_blank">the PHP docs</a> for date formats. Otherwise, enter the number of different time units to display, which defaults to 2.'),
merlinofchaos's avatar
merlinofchaos committed
108 109
      '#default_value' => isset($this->options['custom_date_format']) ? $this->options['custom_date_format'] : '',
    );
110 111 112 113 114 115
    // Setup #states for all possible date_formats on the custom_date_format form element.
    foreach (array('custom', 'raw time ago', 'time ago', 'raw time hence', 'time hence', 'raw time span', 'time span', 'raw time span', 'inverse time span', 'time span') as $custom_date_possible) {
      $form['custom_date_format']['#states']['visible'][] = array(
        ':input[name="options[date_format]"]' => array('value' => $custom_date_possible),
      );
    }
116 117 118 119 120 121 122 123 124 125 126 127
    $form['timezone'] = array(
      '#type' => 'select',
      '#title' => t('Timezone'),
      '#description' => t('Timezone to be used for date output.'),
      '#options' => array('' => t('- Default site/user timezone -')) + system_time_zones(FALSE),
      '#default_value' => $this->options['timezone'],
    );
    foreach (array_merge(array('custom'), array_keys($date_formats)) as $timezone_date_formats) {
      $form['timezone']['#states']['visible'][] = array(
        ':input[name="options[date_format]"]' => array('value' => $timezone_date_formats),
      );
    }
merlinofchaos's avatar
merlinofchaos committed
128

129
    parent::buildOptionsForm($form, $form_state);
merlinofchaos's avatar
merlinofchaos committed
130 131
  }

132 133 134 135
  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
136
    $value = $this->getValue($values);
merlinofchaos's avatar
merlinofchaos committed
137 138 139 140 141 142
    $format = $this->options['date_format'];
    if (in_array($format, array('custom', 'raw time ago', 'time ago', 'raw time hence', 'time hence', 'raw time span', 'time span', 'raw time span', 'inverse time span', 'time span'))) {
      $custom_format = $this->options['custom_date_format'];
    }

    if ($value) {
143
      $timezone = !empty($this->options['timezone']) ? $this->options['timezone'] : NULL;
merlinofchaos's avatar
merlinofchaos committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
      $time_diff = REQUEST_TIME - $value; // will be positive for a datetime in the past (ago), and negative for a datetime in the future (hence)
      switch ($format) {
        case 'raw time ago':
          return format_interval($time_diff, is_numeric($custom_format) ? $custom_format : 2);
        case 'time ago':
          return t('%time ago', array('%time' => format_interval($time_diff, is_numeric($custom_format) ? $custom_format : 2)));
        case 'raw time hence':
          return format_interval(-$time_diff, is_numeric($custom_format) ? $custom_format : 2);
        case 'time hence':
          return t('%time hence', array('%time' => format_interval(-$time_diff, is_numeric($custom_format) ? $custom_format : 2)));
        case 'raw time span':
          return ($time_diff < 0 ? '-' : '') . format_interval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2);
        case 'inverse time span':
          return ($time_diff > 0 ? '-' : '') . format_interval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2);
        case 'time span':
          return t(($time_diff < 0 ? '%time hence' : '%time ago'), array('%time' => format_interval(abs($time_diff), is_numeric($custom_format) ? $custom_format : 2)));
        case 'custom':
          if ($custom_format == 'r') {
162
            return format_date($value, $format, $custom_format, $timezone, 'en');
merlinofchaos's avatar
merlinofchaos committed
163
          }
164
          return format_date($value, $format, $custom_format, $timezone);
merlinofchaos's avatar
merlinofchaos committed
165
        default:
166
          return format_date($value, $format, '', $timezone);
merlinofchaos's avatar
merlinofchaos committed
167 168 169
      }
    }
  }
170

merlinofchaos's avatar
merlinofchaos committed
171
}