ckeditor_taxonomy_glossary-1.0.0-alpha1/src/Plugin/Filter/GlossaryLinkFilter.php

src/Plugin/Filter/GlossaryLinkFilter.php
<?php

declare(strict_types=1);

namespace Drupal\ckeditor_taxonomy_glossary\Plugin\Filter;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a filter to process glossary links.
 *
 * @Filter(
 *   id = "ckeditor_taxonomy_glossary_link",
 *   title = @Translation("Glossary link filter"),
 *   description = @Translation("Processes glossary links and attaches tooltip functionality."),
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
 * )
 */
final class GlossaryLinkFilter extends FilterBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs a GlossaryLinkFilter 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\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    /**
     * The entity type manager.
     */
    protected EntityTypeManagerInterface $entityTypeManager,
    /**
     * The config factory.
     */
    protected ConfigFactoryInterface $configFactory
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('config.factory')
    );
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function process($text, $langcode): FilterProcessResult {
    $result = new FilterProcessResult($text);

    // Check if there are any glossary links in the text.
    if (!str_contains($text, 'glossary-link') && !str_contains($text, 'data-glossary-id')) {
      return $result;
    }

    // Find all glossary term IDs in the text.
    $term_ids = [];
    if (preg_match_all('/data-glossary-id="(\d+)"/', $text, $matches)) {
      $term_ids = array_unique($matches[1]);
    }

    if (empty($term_ids)) {
      return $result;
    }

    // Get glossary settings.
    $config = $this->configFactory->get('ckeditor_taxonomy_glossary.settings');
    $link_style = $config->get('link_style') ?? 'dotted';
    $max_width = $config->get('max_width') ?? 320;
    $show_on_hover = $config->get('show_on_hover') ?? TRUE;
    $show_on_click = $config->get('show_on_click') ?? TRUE;
    $delay = $config->get('delay') ?? 200;
    $show_close_button = $config->get('show_close_button') ?? FALSE;
    $cache_duration = $config->get('cache_duration') ?? '3600';
    $preload_descriptions = $config->get('preload_descriptions') ?? TRUE;

    // Attach the tooltip library and settings.
    $attachments = [
      'library' => ['ckeditor_taxonomy_glossary/glossary_tooltip'],
      'drupalSettings' => [
        'ckeditorTaxonomyGlossary' => [
          'linkStyle' => $link_style,
          'maxWidth' => $max_width,
          'showOnHover' => $show_on_hover,
          'showOnClick' => $show_on_click,
          'delay' => $delay,
          'showCloseButton' => $show_close_button,
          'cacheDuration' => $cache_duration,
        ],
      ],
    ];

    // If preloading is enabled, load term descriptions.
    if ($preload_descriptions) {
      /** @var \Drupal\taxonomy\TermStorageInterface $term_storage */
      $term_storage = $this->entityTypeManager->getStorage('taxonomy_term');
      $terms = $term_storage->loadMultiple($term_ids);

      $glossary_data = [];
      foreach ($terms as $term) {
        if ($term->bundle() === 'glossary') {
          // Use translated version if available
          $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
          if ($term->hasTranslation($current_language)) {
            $term = $term->getTranslation($current_language);
          }

          $description = '';
          if ($term->hasField('description') && !$term->get('description')->isEmpty()) {
            $description = $term->get('description')->processed;
          }

          $glossary_data[$term->id()] = [
            'name'        => $term->getName(),
            'description' => $description,
          ];

          // Add cache dependency.
          $result->addCacheableDependency($term);
        }
      }

      if (!empty($glossary_data)) {
        $attachments['drupalSettings']['ckeditorTaxonomyGlossary']['terms'] = $glossary_data;
      }
    }

    $result->setAttachments($attachments);

    // Add cache dependencies.
    $result->addCacheableDependency($config);
    $result->addCacheTags(['taxonomy_term_list:glossary']);

    return $result;
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function tips($long = FALSE) {
    if ($long) {
      return $this->t('Glossary links will display tooltips with term descriptions when users hover over or click on them.');
    }
    return $this->t('Glossary links are processed to show tooltips.');
  }
}

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

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