xandeadx

GLM 5.2 (free)

Jun 25th, 2026 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.36 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Drupal\my_module\Plugin\Block;
  4.  
  5. use Drupal\Core\Block\BlockBase;
  6. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Drupal\Core\Datetime\DateFormatterInterface;
  9. use Drupal\Component\Datetime\TimeInterface;
  10. use Drupal\Core\Form\FormStateInterface;
  11.  
  12. /**
  13.  * Предоставляет блок 'Текущий день'.
  14.  *
  15.  * @Block(
  16.  *   id = "current_day_block",
  17.  *   admin_label = @Translation("Текущий день"),
  18.  *   category = @Translation("Custom"),
  19.  * )
  20.  */
  21. class CurrentDayBlock extends BlockBase implements ContainerFactoryPluginInterface {
  22.  
  23.   /**
  24.    * Сервис форматирования даты.
  25.    *
  26.    * @var \Drupal\Core\Datetime\DateFormatterInterface
  27.    */
  28.   protected $dateFormatter;
  29.  
  30.   /**
  31.    * Сервис времени.
  32.    *
  33.    * @var \Drupal\Component\Datetime\TimeInterface
  34.    */
  35.   protected $time;
  36.  
  37.   /**
  38.    * Конструктор плагина блока.
  39.    */
  40.   public function __construct(
  41.     array $configuration,
  42.     $plugin_id,
  43.     $plugin_definition,
  44.     DateFormatterInterface $date_formatter,
  45.     TimeInterface $time
  46.   ) {
  47.     parent::__construct($configuration, $plugin_id, $plugin_definition);
  48.     $this->dateFormatter = $date_formatter;
  49.     $this->time = $time;
  50.   }
  51.  
  52.   /**
  53.    * {@inheritdoc}
  54.    */
  55.   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  56.     return new static(
  57.       $configuration,
  58.       $plugin_id,
  59.       $plugin_definition,
  60.       $container->get('date.formatter'),
  61.       $container->get('datetime.time')
  62.     );
  63.   }
  64.  
  65.   /**
  66.    * {@inheritdoc}
  67.    */
  68.   public function defaultConfiguration() {
  69.     // Задаем настройки по умолчанию: формат даты и заголовок блока.
  70.     return [
  71.       'date_format' => 'l, d.m.Y',
  72.       'label' => 'Текущий день',
  73.       'label_display' => TRUE,
  74.     ] + parent::defaultConfiguration();
  75.   }
  76.  
  77.   /**
  78.    * {@inheritdoc}
  79.    */
  80.   public function blockForm($form, FormStateInterface $form_state) {
  81.     // Добавляем поле настройки формата даты в стандартную форму настройки блока.
  82.     $form['date_format'] = [
  83.       '#type' => 'textfield',
  84.       '#title' => $this->t('Формат даты (PHP DateTime формат)'),
  85.       '#description' => $this->t('Используйте синтаксис PHP. Например: <em>d.m.Y</em> (01.01.2024) или <em>l, j F</em> (Понедельник, 1 Января). <a href="https://www.php.net/manual/ru/datetime.format.php">Документация PHP</a>.'),
  86.       '#default_value' => $this->configuration['date_format'],
  87.       '#required' => TRUE,
  88.     ];
  89.  
  90.     return $form;
  91.   }
  92.  
  93.   /**
  94.    * {@inheritdoc}
  95.    */
  96.   public function blockSubmit($form, FormStateInterface $form_state) {
  97.     // Сохраняем значение настройки.
  98.     $this->configuration['date_format'] = $form_state->getValue('date_format');
  99.   }
  100.  
  101.   /**
  102.    * {@inheritdoc}
  103.    */
  104.   public function build() {
  105.     // Получаем текущее время (timestamp).
  106.     $now = $this->time->getCurrentTime();
  107.     // Форматируем дату с учетом выбранного формата.
  108.     $formatted_date = $this->dateFormatter->format($now, 'custom', $this->configuration['date_format']);
  109.  
  110.     // Вычисляем количество секунд до полуночи для сброса кэша блока.
  111.     $datetime = new \DateTime();
  112.     $datetime->setTimestamp($now);
  113.     $datetime->setTime(23, 59, 59);
  114.     $seconds_until_midnight = $datetime->getTimestamp() - $now + 1;
  115.  
  116.     return [
  117.       '#theme' => 'current_day_block',
  118.       '#date' => $formatted_date,
  119.       // Прячем стандартный заголовок, так как мы будем выводить его в шаблоне,
  120.       // ИЛИ можно оставить рендер заголовка через '#title' (смотри пояснения ниже).
  121.       '#attached' => [
  122.         'library' => [],
  123.       ],
  124.       '#cache' => [
  125.         'max-age' => $seconds_until_midnight,
  126.         'contexts' => ['timezone'], // Кэш зависит от часового пояса пользователя
  127.       ],
  128.     ];
  129.   }
  130.  
  131. }
Add Comment
Please, Sign In to add comment