datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/TimestampAgoFormatter.php

src/Plugin/DataField/FieldFormatter/TimestampAgoFormatter.php
<?php

namespace Drupal\datafield\Plugin\DataField\FieldFormatter;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\datafield\Plugin\DataFieldFormatterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the 'timestamp' formatter as time ago.
 */
#[FieldFormatter(
  id: 'timestamp_ago',
  label: new TranslatableMarkup('Time ago'),
  field_types: ['datetime_iso8601', 'date'],
)]
class TimestampAgoFormatter implements DataFieldFormatterInterface, ContainerFactoryPluginInterface {
  use StringTranslationTrait;

  /**
   * Constructs a TimestampFormatter object.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param mixed $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
   *   The date formatter service.
   */
  public function __construct($plugin_id, $plugin_definition, $field_definition, protected EntityTypeManagerInterface $entityTypeManager, protected readonly DateFormatterInterface $dateFormatter) {
    unset($plugin_id, $plugin_definition, $field_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration,
      $container->get('entity_type.manager'),
      $container->get('date.formatter'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'future_format' => '@interval hence',
      'past_format' => '@interval ago',
      'granularity' => 2,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {

    $settings = $form['#settings'];

    $element['future_format'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Future format'),
      '#default_value' => $settings['future_format'] ?? self::defaultSettings()['future_format'],
      '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
    ];

    $element['past_format'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Past format'),
      '#default_value' => $settings['past_format'] ?? self::defaultSettings()['past_format'],
      '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
    ];

    $element['granularity'] = [
      '#type' => 'number',
      '#title' => $this->t('Granularity'),
      '#description' => $this->t('How many time interval units should be shown in the formatted output.'),
      '#default_value' => $settings['granularity'] ?? self::defaultSettings()['granularity'],
      '#min' => 1,
      '#max' => 6,
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary($settings = []) {
    $settings += self::defaultSettings();
    $future_date = new DrupalDateTime('1 year 1 month 1 week 1 day 1 hour 1 minute');
    $past_date = new DrupalDateTime('-1 year -1 month -1 week -1 day -1 hour -1 minute');
    $options = [
      'granularity' => $settings['granularity'],
      'return_as_object' => FALSE,
    ];

    $future_date_interval = new FormattableMarkup($settings['future_format'], ['@interval' => $this->dateFormatter->formatTimeDiffUntil($future_date->getTimestamp(), $options)]);
    $past_date_interval = new FormattableMarkup($settings['past_format'], ['@interval' => $this->dateFormatter->formatTimeDiffSince($past_date->getTimestamp(), $options)]);

    $summary[] = $this->t('Future date: %display', ['%display' => $future_date_interval]);
    $summary[] = $this->t('Past date: %display', ['%display' => $past_date_interval]);

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements($item, $langcode) {
    if (!empty($item->value)) {
      $timestamp = is_numeric($item->value) ? $item->value : strtotime($item->value);
      $updated = $this->formatTimestamp($timestamp, $item->settings);
    }
    else {
      $updated = [
        '#markup' => $this->t('never'),
      ];
    }
    return $updated;
  }

  /**
   * Formats a timestamp.
   *
   * @param int $timestamp
   *   A UNIX timestamp to format.
   * @param array $settings
   *   Setting formatter.
   *
   * @return array
   *   The formatted timestamp string using the past or future format setting.
   */
  protected function formatTimestamp($timestamp, array $settings = []) {
    $granularity = $settings['granularity'] ?? self::defaultSettings()['granularity'];
    $options = [
      'granularity' => $granularity,
      'return_as_object' => TRUE,
    ];
    $serverTimestamp = $_SERVER['REQUEST_TIME'];
    if ($serverTimestamp > $timestamp) {
      $result = $this->dateFormatter->formatTimeDiffSince($timestamp, $options);
      $build = [
        '#markup' => new FormattableMarkup(
          $settings['past_format'] ?? self::defaultSettings()['past_format'],
          ['@interval' => $result->getString()]
        ),
      ];
    }
    else {
      $result = $this->dateFormatter->formatTimeDiffUntil($timestamp, $options);
      $build = [
        '#markup' => new FormattableMarkup(
          $settings['future_format'] ?? self::defaultSettings()['future_format'],
          ['@interval' => $result->getString()]
        ),
      ];
    }
    CacheableMetadata::createFromObject($result)->applyTo($build);
    return $build;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc