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

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

namespace Drupal\datafield\Plugin\DataField\FieldFormatter;

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.
 */
#[FieldFormatter(
  id: 'timestamp',
  label: new TranslatableMarkup('Default'),
  field_types: ['datetime_iso8601', 'date'],
)]
class TimestampFormatter 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 [
      'date_format' => 'medium',
      'custom_date_format' => '',
      'timezone' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $settings = $form['#settings'];
    $subfield = $form['#machine_name'];

    $format_types = $this->entityTypeManager->getStorage('date_format')->loadMultiple();
    $time = new DrupalDateTime();
    $options['custom'] = $this->t('Custom date format');
    foreach ($format_types as $type => $type_info) {
      $format = $this->dateFormatter->format($time->getTimestamp(), $type);
      $options[$type] = $type_info->label() . ' (' . $format . ')';
    }
    $elements['date_format'] = [
      '#type' => 'select',
      '#title' => $this->t('Date format'),
      '#description' => $this->t('Choose a format for displaying the date.'),
      '#options' => $options,
      '#default_value' => $settings['date_format'] ?? '',
    ];
    $visible = 'select[name*="[settings_edit_form][settings][formatter_settings][' . $subfield . '][date_format]"]';
    $elements['custom_date_format'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Custom date format'),
      '#description' => $this->t('See <a href="https://www.php.net/manual/datetime.format.php#refsect1-datetime.format-parameters" target="_blank">the documentation for PHP date formats</a>.'),
      '#default_value' => $settings['custom_date_format'] ?? '',
      '#states' => [
        'visible' => [$visible => ['value' => 'custom']],
      ],
    ];

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary($settings = []) {
    $summary = [];
    $date_format = $settings['date_format'] ?? NULL;
    $summary[] = $this->t('Date format: @date_format', ['@date_format' => $date_format]);
    if (!empty($settings['date_format']) && $settings['date_format'] === 'custom' && ($custom_date_format = $settings['custom_date_format'])) {
      $summary[] = $this->t('Custom date format: @custom_date_format', ['@custom_date_format' => $custom_date_format]);
    }
    if ($timezone = $settings['timezone'] ?? NULL) {
      $summary[] = $this->t('Time zone: @timezone', ['@timezone' => $timezone]);
    }

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements($item, $langcode) {
    if (empty($item->value)) {
      return $item->value;
    }
    $isDate = in_array($item->storage["type"], ['date', 'datetime_iso8601']);
    if (empty($item->settings) && $isDate) {
      $valueTypeText = ['time', 'year', 'month', 'week'];
      if (in_array($item->storage["datetime_type"], $valueTypeText)) {
        return [
          '#cache' => [
            'contexts' => [
              'timezone',
            ],
          ],
          '#markup' => $item->value,
        ];
      }
    }
    $date_format = $item->settings['date_format'] ?? self::defaultSettings()['date_format'];
    $custom_date_format = '';
    $timezone = $item->settings['timezone'] ?? NULL;
    // If an RFC2822 date format is requested, then the month and day have to
    // be in English. @see http://www.faqs.org/rfcs/rfc2822.html
    if ($date_format === 'custom' && ($custom_date_format = $item->settings['custom_date_format']) === 'r') {
      $langcode = 'en';
    }
    $timestamp = is_numeric($item->value) ? $item->value : strtotime($item->value);
    return [
      '#cache' => [
        'contexts' => [
          'timezone',
        ],
      ],
      '#markup' => $this->dateFormatter->format($timestamp, $date_format, $custom_date_format, $timezone, $langcode),
    ];
  }

}

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

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