Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- declare(strict_types=1);
- namespace Drupal\current_date\Plugin\Block;
- use Drupal\Component\Datetime\TimeInterface;
- use Drupal\Core\Block\Attribute\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\Core\Cache\Cache;
- use Drupal\Core\Datetime\DateFormatterInterface;
- use Drupal\Core\Entity\EntityStorageInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
- use Drupal\Core\StringTranslation\TranslatableMarkup;
- use Symfony\Component\DependencyInjection\ContainerInterface;
- /**
- * Provides a block that displays the current date.
- */
- #[Block(
- id: 'current_date_block',
- admin_label: new TranslatableMarkup('Current date'),
- category: new TranslatableMarkup('Custom'),
- )]
- class CurrentDateBlock extends BlockBase implements ContainerFactoryPluginInterface {
- /**
- * Machine name of the custom date format option.
- */
- protected const CUSTOM_DATE_FORMAT = 'custom';
- /**
- * Constructs a CurrentDateBlock object.
- *
- * @param array $configuration
- * A configuration array containing information about the plugin instance.
- * @param string $plugin_id
- * The plugin ID for the plugin instance.
- * @param mixed $plugin_definition
- * The plugin implementation definition.
- * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
- * The date formatter service.
- * @param \Drupal\Core\Entity\EntityStorageInterface $dateFormatStorage
- * The date format entity storage.
- * @param \Drupal\Component\Datetime\TimeInterface $time
- * The time service.
- */
- public function __construct(
- array $configuration,
- $plugin_id,
- $plugin_definition,
- protected DateFormatterInterface $dateFormatter,
- protected EntityStorageInterface $dateFormatStorage,
- protected TimeInterface $time,
- ) {
- parent::__construct($configuration, $plugin_id, $plugin_definition);
- }
- /**
- * {@inheritdoc}
- */
- public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
- return new static(
- $configuration,
- $plugin_id,
- $plugin_definition,
- $container->get('date.formatter'),
- $container->get('entity_type.manager')->getStorage('date_format'),
- $container->get('datetime.time'),
- );
- }
- /**
- * {@inheritdoc}
- */
- public function defaultConfiguration(): array {
- return [
- 'label_display' => TRUE,
- 'date_format' => 'medium',
- 'custom_date_format' => '',
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function blockForm($form, FormStateInterface $form_state): array {
- $request_time = $this->time->getRequestTime();
- $date_formats = [];
- foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $date_format) {
- $date_formats[$machine_name] = $this->t('@name format: @date', [
- '@name' => $date_format->label(),
- '@date' => $this->dateFormatter->format($request_time, $machine_name),
- ]);
- }
- $date_formats[static::CUSTOM_DATE_FORMAT] = $this->t('Custom');
- $form['date_format'] = [
- '#type' => 'select',
- '#title' => $this->t('Date format'),
- '#options' => $date_formats,
- '#default_value' => $this->configuration['date_format'],
- '#required' => TRUE,
- ];
- $form['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' => $this->configuration['custom_date_format'],
- '#states' => [
- 'visible' => [
- ':input[name="settings[date_format]"]' => ['value' => static::CUSTOM_DATE_FORMAT],
- ],
- 'required' => [
- ':input[name="settings[date_format]"]' => ['value' => static::CUSTOM_DATE_FORMAT],
- ],
- ],
- ];
- return $form;
- }
- /**
- * {@inheritdoc}
- */
- public function blockSubmit($form, FormStateInterface $form_state): void {
- $this->configuration['date_format'] = $form_state->getValue('date_format');
- $this->configuration['custom_date_format'] = $form_state->getValue('custom_date_format') ?? '';
- }
- /**
- * {@inheritdoc}
- */
- public function build(): array {
- $date_format = $this->configuration['date_format'];
- $custom_date_format = $date_format === static::CUSTOM_DATE_FORMAT
- ? ($this->configuration['custom_date_format'] ?? '')
- : '';
- $timestamp = $this->time->getRequestTime();
- $formatted = $this->dateFormatter->format($timestamp, $date_format, $custom_date_format);
- return [
- '#markup' => $formatted,
- '#cache' => [
- // Date changes every second; avoid caching a stale value for long.
- 'max-age' => 0,
- ],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function getCacheMaxAge(): int {
- return 0;
- }
- /**
- * {@inheritdoc}
- */
- public function getCacheTags(): array {
- $tags = parent::getCacheTags();
- $date_format = $this->configuration['date_format'] ?? '';
- if ($date_format !== '' && $date_format !== static::CUSTOM_DATE_FORMAT) {
- $tags = Cache::mergeTags($tags, ['config:core.date_format.' . $date_format]);
- }
- return $tags;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment