xandeadx

Grok 4.5 (paid)

Jul 26th, 2026
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.38 KB | None | 0 0
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace Drupal\current_date\Plugin\Block;
  6.  
  7. use Drupal\Component\Datetime\TimeInterface;
  8. use Drupal\Core\Block\Attribute\Block;
  9. use Drupal\Core\Block\BlockBase;
  10. use Drupal\Core\Cache\Cache;
  11. use Drupal\Core\Datetime\DateFormatterInterface;
  12. use Drupal\Core\Entity\EntityStorageInterface;
  13. use Drupal\Core\Form\FormStateInterface;
  14. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  15. use Drupal\Core\StringTranslation\TranslatableMarkup;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17.  
  18. /**
  19.  * Provides a block that displays the current date.
  20.  */
  21. #[Block(
  22.  id: 'current_date_block',
  23.   admin_label: new TranslatableMarkup('Current date'),
  24.   category: new TranslatableMarkup('Custom'),
  25. )]
  26. class CurrentDateBlock extends BlockBase implements ContainerFactoryPluginInterface {
  27.  
  28.   /**
  29.    * Machine name of the custom date format option.
  30.    */
  31.   protected const CUSTOM_DATE_FORMAT = 'custom';
  32.  
  33.   /**
  34.    * Constructs a CurrentDateBlock object.
  35.    *
  36.    * @param array $configuration
  37.    *   A configuration array containing information about the plugin instance.
  38.    * @param string $plugin_id
  39.    *   The plugin ID for the plugin instance.
  40.    * @param mixed $plugin_definition
  41.    *   The plugin implementation definition.
  42.    * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
  43.    *   The date formatter service.
  44.    * @param \Drupal\Core\Entity\EntityStorageInterface $dateFormatStorage
  45.    *   The date format entity storage.
  46.    * @param \Drupal\Component\Datetime\TimeInterface $time
  47.    *   The time service.
  48.    */
  49.   public function __construct(
  50.     array $configuration,
  51.     $plugin_id,
  52.     $plugin_definition,
  53.     protected DateFormatterInterface $dateFormatter,
  54.     protected EntityStorageInterface $dateFormatStorage,
  55.     protected TimeInterface $time,
  56.   ) {
  57.     parent::__construct($configuration, $plugin_id, $plugin_definition);
  58.   }
  59.  
  60.   /**
  61.    * {@inheritdoc}
  62.    */
  63.   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
  64.     return new static(
  65.       $configuration,
  66.       $plugin_id,
  67.       $plugin_definition,
  68.       $container->get('date.formatter'),
  69.       $container->get('entity_type.manager')->getStorage('date_format'),
  70.       $container->get('datetime.time'),
  71.     );
  72.   }
  73.  
  74.   /**
  75.    * {@inheritdoc}
  76.    */
  77.   public function defaultConfiguration(): array {
  78.     return [
  79.       'label_display' => TRUE,
  80.       'date_format' => 'medium',
  81.       'custom_date_format' => '',
  82.     ];
  83.   }
  84.  
  85.   /**
  86.    * {@inheritdoc}
  87.    */
  88.   public function blockForm($form, FormStateInterface $form_state): array {
  89.     $request_time = $this->time->getRequestTime();
  90.     $date_formats = [];
  91.     foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $date_format) {
  92.       $date_formats[$machine_name] = $this->t('@name format: @date', [
  93.         '@name' => $date_format->label(),
  94.         '@date' => $this->dateFormatter->format($request_time, $machine_name),
  95.       ]);
  96.     }
  97.     $date_formats[static::CUSTOM_DATE_FORMAT] = $this->t('Custom');
  98.  
  99.     $form['date_format'] = [
  100.       '#type' => 'select',
  101.       '#title' => $this->t('Date format'),
  102.       '#options' => $date_formats,
  103.       '#default_value' => $this->configuration['date_format'],
  104.       '#required' => TRUE,
  105.     ];
  106.  
  107.     $form['custom_date_format'] = [
  108.       '#type' => 'textfield',
  109.       '#title' => $this->t('Custom date format'),
  110.       '#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>.'),
  111.       '#default_value' => $this->configuration['custom_date_format'],
  112.       '#states' => [
  113.         'visible' => [
  114.           ':input[name="settings[date_format]"]' => ['value' => static::CUSTOM_DATE_FORMAT],
  115.         ],
  116.         'required' => [
  117.           ':input[name="settings[date_format]"]' => ['value' => static::CUSTOM_DATE_FORMAT],
  118.         ],
  119.       ],
  120.     ];
  121.  
  122.     return $form;
  123.   }
  124.  
  125.   /**
  126.    * {@inheritdoc}
  127.    */
  128.   public function blockSubmit($form, FormStateInterface $form_state): void {
  129.     $this->configuration['date_format'] = $form_state->getValue('date_format');
  130.     $this->configuration['custom_date_format'] = $form_state->getValue('custom_date_format') ?? '';
  131.   }
  132.  
  133.   /**
  134.    * {@inheritdoc}
  135.    */
  136.   public function build(): array {
  137.     $date_format = $this->configuration['date_format'];
  138.     $custom_date_format = $date_format === static::CUSTOM_DATE_FORMAT
  139.       ? ($this->configuration['custom_date_format'] ?? '')
  140.       : '';
  141.  
  142.     $timestamp = $this->time->getRequestTime();
  143.     $formatted = $this->dateFormatter->format($timestamp, $date_format, $custom_date_format);
  144.  
  145.     return [
  146.       '#markup' => $formatted,
  147.       '#cache' => [
  148.         // Date changes every second; avoid caching a stale value for long.
  149.         'max-age' => 0,
  150.       ],
  151.     ];
  152.   }
  153.  
  154.   /**
  155.    * {@inheritdoc}
  156.    */
  157.   public function getCacheMaxAge(): int {
  158.     return 0;
  159.   }
  160.  
  161.   /**
  162.    * {@inheritdoc}
  163.    */
  164.   public function getCacheTags(): array {
  165.     $tags = parent::getCacheTags();
  166.     $date_format = $this->configuration['date_format'] ?? '';
  167.     if ($date_format !== '' && $date_format !== static::CUSTOM_DATE_FORMAT) {
  168.       $tags = Cache::mergeTags($tags, ['config:core.date_format.' . $date_format]);
  169.     }
  170.     return $tags;
  171.   }
  172.  
  173. }
  174.  
Advertisement
Add Comment
Please, Sign In to add comment