aero_weather-1.0.3/src/Plugin/Block/AeroWeatherHorizontalBlock.php

src/Plugin/Block/AeroWeatherHorizontalBlock.php
<?php

namespace Drupal\aero_weather\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\aero_weather\Service\AeroWeatherApi;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\file\FileUsage\FileUsageInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\File\FileUrlGeneratorInterface;

/**
 * Provides an 'Aero Weather' block.
 *
 * @Block(
 *   id = "aero_weather_horizontal_block",
 *   admin_label = @Translation("Aero Weather (Horizontal)"),
 *   category = @Translation("Aero Weather")
 * )
 */
class AeroWeatherHorizontalBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The exchange rate API service.
   *
   * @var \Drupal\aero_weather\Service\AeroWeatherApi
   */
  protected $apiService;

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The file usage service.
   *
   * @var \Drupal\file\FileUsage\FileUsageInterface
   */
  protected $fileUsage;

  /**
   * The entity repository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * The cache service.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * The file URL generator service.
   *
   * Used to generate absolute or relative URLs for file entities.
   *
   * @var \Drupal\Core\Url\FileUrlGeneratorInterface
   */
  protected $fileUrlGenerator;

  /**
   * Constructs a new AeroWeatherHorizontalBlock 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\aero_weather\Service\AeroWeatherApi $api_service
   *   The exchange rate API service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\file\FileUsage\FileUsageInterface $file_usage
   *   The file usage service.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The cache service.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter service.
   * @param \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator
   *   The file URL generator service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AeroWeatherApi $api_service, EntityTypeManagerInterface $entity_type_manager, FileUsageInterface $file_usage, EntityRepositoryInterface $entity_repository, CacheBackendInterface $cache, DateFormatterInterface $date_formatter, FileUrlGeneratorInterface $file_url_generator) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->apiService = $api_service;
    $this->entityTypeManager = $entity_type_manager;
    $this->fileUsage = $file_usage;
    $this->entityRepository = $entity_repository;
    $this->cache = $cache;
    $this->dateFormatter = $date_formatter;
    $this->fileUrlGenerator = $file_url_generator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('aero_weather.api'),
      $container->get('entity_type.manager'),
      $container->get('file.usage'),
      $container->get('entity.repository'),
      $container->get('cache.default'),
      $container->get('date.formatter'),
      $container->get('file_url_generator')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Get selected countries with their order.
    $location_name = $this->configuration['location_name'];
    $date_format = $this->configuration['date_format'];
    $color_palette = $this->configuration['color_palette'];
    $round_border = $this->configuration['round_border'];
    $forecast_days = $this->configuration['forecast_days'];

    $weather_data = $this->apiService->getWeatherData($location_name, $forecast_days);
    $icon_settings = $this->apiService->getWeatherIconSettings();

    // Check if the timestamp exists before attempting to format it.
    $formatted_date = '';
    if (isset($weather_data['location']['localtime_epoch'])) {
      // Use the injected date formatter service to convert the epoch timestamp
      // into a human-readable string based on the selected format.
      $formatted_date = $this->dateFormatter->format($weather_data['location']['localtime_epoch'], $date_format);
    }
    $uuid = aero_weather_generate_weather_card_uuid();

    // Get uploaded background_image URL if exists.
    $background_image_url = '';
    if (!empty($this->configuration['background_image'])) {
      $file = $this->entityTypeManager->getStorage('file')->load($this->configuration['background_image']);
      if ($file) {
        $background_image_url = $this->fileUrlGenerator->generateAbsoluteString($file->getFileUri());
      }
    }

    $enable_swiper_js = $this->configuration['enable_swiper_js'] ?? FALSE;

    $libraries = [
      'aero_weather/color_palettes',
      'aero_weather/aero_weather_horizontal',
    ];

    // Attach swiper only if enabled.
    if ($enable_swiper_js) {
      $libraries[] = 'aero_weather/swiper_cdn';
    }

    return [
      '#theme' => 'aero_weather_horizontal_block',
      '#weather_data' => $weather_data,
      '#config' => [
        'formatted_date' => $formatted_date,
        'color_palette' => $color_palette,
        'round_border' => $round_border,
        'forecast_days' => $forecast_days,
        'uuid' => $uuid,
        'background_image_url' => $background_image_url,
        'icon_settings' => $icon_settings,
      ],
      '#cache' => [
        'keys' => ['aero_weather', 'block_data'],
        'tags' => ['config:aero_weather.settings'],
        'max-age' => 0,
      ],
      '#attached' => [
        'library' => $libraries,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form['settings'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Weather Widget Settings'),
      '#description' => $this->t('Configure the display options for the weather widget.'),
    ];

    $form['settings']['location_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Location Name'),
      '#description' => $this->t('Enter the valid name of the location (e.g., New York, USA) for which weather data will be displayed.'),
      '#default_value' => $this->configuration['location_name'] ?? '',
      '#required' => TRUE,
    ];

    // Load available date formats.
    $date_format_storage = $this->entityTypeManager->getStorage('date_format');
    $formats = $date_format_storage->loadMultiple();

    $date_format_options = [];
    foreach ($formats as $format) {
      $date_format_options[$format->id()] = $format->label();
    }

    $form['settings']['date_format'] = [
      '#type' => 'select',
      '#title' => $this->t('Date format'),
      '#description' => $this->t('Select how dates should be displayed throughout this weather block.'),
      '#options' => $date_format_options,
      '#default_value' => $this->configuration['date_format'] ?? '',
    ];

    $form['settings']['color_palette'] = [
      '#type' => 'select',
      '#title' => $this->t('Color Palette'),
      '#description' => $this->t('Choose a predefined color palette to customize the appearance of the widget.'),
      '#options' => aero_weather_color_palettes(),
      '#default_value' => $this->configuration['color_palette'] ?? 'palette-1',
    ];

    $form['settings']['round_border'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Round Border'),
      '#description' => $this->t('Enable to apply rounded corners to the weather card.'),
      '#default_value' => $this->configuration['round_border'] ?? 0,
    ];

    $form['settings']['enable_swiper_js'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable SwiperJs'),
      '#description' => $this->t('Enable SwiperJs if your site does not already use it.'),
      '#default_value' => $this->configuration['enable_swiper_js'] ?? 0,
    ];

    $form['settings']['background_image'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Upload Image'),
      '#description' => $this->t('Allowed file types: jpg, jpeg, png, gif, webp.'),
      '#default_value' => isset($this->configuration['background_image']) ? [$this->configuration['background_image']] : NULL,
      '#upload_location' => 'public://aero_weather_images/',
      '#upload_validators'  => [
        'FileExtension' => ['extensions' => 'gif png jpg jpeg svg webp'],
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $values = $form_state->getValue('settings');

    // Handle background_image upload.
    if (!empty($values['background_image'][0])) {
      $fid = $values['background_image'][0];
      $file = $this->entityTypeManager->getStorage('file')->load($fid);
      if ($file) {
        $file->setPermanent();
        $file->save();
      }

      // If replacing an old background_image, set old file to temporary.
      if (!empty($this->configuration['background_image']) && $this->configuration['background_image'] != $fid) {
        $old_file = $this->entityTypeManager->getStorage('file')->load($this->configuration['background_image']);
        if ($old_file) {
          $old_file->setTemporary();
          $old_file->save();
        }
      }

      $this->configuration['background_image'] = $fid;
    }
    else {
      // If background_image is removed, set old file to temporary.
      if (!empty($this->configuration['background_image'])) {
        $old_file = $this->entityTypeManager->getStorage('file')->load($this->configuration['background_image']);
        if ($old_file) {
          $old_file->setTemporary();
          $old_file->save();
        }
      }
      $this->configuration['background_image'] = NULL;
    }

    $this->configuration['location_name'] = $values['location_name'];
    $this->configuration['color_palette'] = $values['color_palette'];
    $this->configuration['round_border'] = $values['round_border'];
    $this->configuration['enable_swiper_js'] = $values['enable_swiper_js'];
    $this->configuration['date_format'] = $values['date_format'];
    $this->configuration['forecast_days'] = $values['forecast_days'];
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'date_format' => '',
      'color_palette' => 'palette-1',
      'round_border' => TRUE,
      'enable_swiper_js' => TRUE,
      'forecast_days' => '5',
      'background_image' => NULL,
    ] + parent::defaultConfiguration();
  }

}

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

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