You are here

class MentionsFilter in Open Social 8.2

Same name and namespace in other branches
  1. 8.9 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  2. 8 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  3. 8.3 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  4. 8.4 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  5. 8.5 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  6. 8.6 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  7. 8.7 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  8. 8.8 modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  9. 10.3.x modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  10. 10.0.x modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  11. 10.1.x modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter
  12. 10.2.x modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php \Drupal\mentions\Plugin\Filter\MentionsFilter

Class FilterMentions.

@package Drupal\mentions\Plugin\Filter

Plugin annotation


@Filter(
id = "filter_mentions",
title = @Translation("Mentions Filter"),
description = @Translation("Configure via the <a href='/admin/structure/mentions'>Mention types</a> page."),
type = Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR,
settings = {
  "mentions_filter" = {}
},
weight = -10
)

Hierarchy

Expanded class hierarchy of MentionsFilter

1 file declares its use of MentionsFilter
mentions.module in modules/custom/mentions/mentions.module
Code for the mentions module.

File

modules/custom/mentions/src/Plugin/Filter/MentionsFilter.php, line 35

Namespace

Drupal\mentions\Plugin\Filter
View source
class MentionsFilter extends FilterBase implements ContainerFactoryPluginInterface {
  protected $entityManager;
  protected $renderer;
  protected $config;
  protected $mentionsManager;
  private $tokenService;
  private $mentionTypes = [];
  private $entityQueryService;
  private $inputSettings = [];
  private $outputSettings = [];
  private $textFormat;

  /**
   * MentionsFilter constructor.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_manager, RendererInterface $render, ConfigFactory $config, MentionsPluginManager $mentions_manager, Token $token, QueryFactory $query_factory) {
    $this->entityManager = $entity_manager;
    $this->mentionsManager = $mentions_manager;
    $this->renderer = $render;
    $this->config = $config;
    $this->tokenService = $token;
    $this->entityQueryService = $query_factory;
    if (!isset($plugin_definition['provider'])) {
      $plugin_definition['provider'] = 'mentions';
    }
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $entity_manager = $container
      ->get('entity.manager');
    $renderer = $container
      ->get('renderer');
    $config = $container
      ->get('config.factory');
    $mentions_manager = $container
      ->get('plugin.manager.mentions');
    $token = $container
      ->get('token');
    $entity_service = $container
      ->get('entity.query');
    return new static($configuration, $plugin_id, $plugin_definition, $entity_manager, $renderer, $config, $mentions_manager, $token, $entity_service);
  }

  /**
   * Returns the settings.
   *
   * @return array
   *   A list of settings.
   */
  public function getSettings() {
    return $this->settings;
  }

  /**
   * Checks if there are mentionTypes.
   *
   * @return bool
   *   TRUE if there are mentionTypes, otherwise FALSE.
   */
  public function checkMentionTypes() {
    $settings = $this->settings;
    if (isset($settings['mentions_filter'])) {
      $configs = $this->config
        ->listAll('mentions.mentions_type');
      foreach ($configs as $config) {
        $this->mentionTypes[] = str_replace('mentions.mentions_type.', '', $config);
      }
    }
    return !empty($this->mentionTypes);
  }

  /**
   * Checks if a textFormat filter should be applied.
   *
   * @return bool
   *   TRUE if filter should applied, otherwise FALSE.
   */
  public function shouldApplyFilter() {
    if ($this
      ->checkMentionTypes()) {
      return TRUE;
    }
    elseif ($this->textFormat && ($format = FilterFormat::load($this->textFormat))) {
      $filters = $format
        ->get('filters');
      if (!empty($filters['filter_mentions']['status'])) {
        $this->settings = $filters['filter_mentions']['settings'];
        return $this
          ->checkMentionTypes();
      }
    }
    return FALSE;
  }

  /**
   * Gets the mentions in text.
   *
   * @param string $text
   *   The text to find mentions in.
   *
   * @return array
   *   A list of mentions.
   */
  public function getMentions($text) {
    $mentions = [];
    $config_names = $this->mentionTypes;
    foreach ($config_names as $config_name) {
      $settings = $this->config
        ->get('mentions.mentions_type.' . $config_name);
      $input_settings = [
        'prefix' => $settings
          ->get('input.prefix'),
        'suffix' => $settings
          ->get('input.suffix'),
        'entity_type' => $settings
          ->get('input.entity_type'),
        'value' => $settings
          ->get('input.inputvalue'),
      ];
      $this->inputSettings[$config_name] = $input_settings;
      if (!isset($input_settings['entity_type']) || empty($this->settings['mentions_filter'][$config_name])) {
        continue;
      }
      $output_settings = [
        'value' => $settings
          ->get('output.outputvalue'),
        'renderlink' => (bool) $settings
          ->get('output.renderlink'),
        'rendertextbox' => $settings
          ->get('output.renderlinktextbox'),
      ];
      $this->outputSettings[$config_name] = $output_settings;
      $mention_type = $settings
        ->get('mention_type');
      $mention = $this->mentionsManager
        ->createInstance($mention_type);
      if ($mention instanceof MentionsPluginInterface) {
        $pattern = '/(?:' . preg_quote($input_settings['prefix']) . ')([a-zA-Z0-9_]+)' . preg_quote($input_settings['suffix']) . '/';
        preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);
        foreach ($matches as $match) {
          $target = $mention
            ->targetCallback($match[1], $input_settings);
          if ($target !== FALSE) {
            $mentions[$match[0]] = [
              'type' => $mention_type,
              'source' => [
                'string' => $match[0],
                'match' => $match[1],
              ],
              'target' => $target,
              'config_name' => $config_name,
            ];
          }
        }
      }
    }
    return $mentions;
  }

  /**
   * Filters mentions in a text.
   *
   * @param string $text
   *   The text containing the possible mentions.
   *
   * @return string
   *   The processed text.
   */
  public function filterMentions($text) {
    $mentions = $this
      ->getMentions($text);
    foreach ($mentions as $match) {
      $mention = $this->mentionsManager
        ->createInstance($match['type']);
      if ($mention instanceof MentionsPluginInterface) {
        $output_settings = $this->outputSettings[$match['config_name']];
        $output = $mention
          ->outputCallback($match, $output_settings);
        $build = [
          '#theme' => 'mention_link',
          '#mention_id' => $match['target']['entity_id'],
          '#link' => $output['link'],
          '#render_link' => $output_settings['renderlink'],
          '#render_value' => $output['value'],
        ];
        $mentions = $this->renderer
          ->render($build);
        $text = str_replace($match['source']['string'], $mentions, $text);
      }
    }
    return $text;
  }

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    if ($this
      ->shouldApplyFilter()) {
      $text = $this
        ->filterMentions($text);
      return new FilterProcessResult($text);
    }
    return new FilterProcessResult($text);
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $configs = $this->config
      ->listAll('mentions.mentions_type');
    $candidate_entitytypes = [];
    foreach ($configs as $config) {
      $mentions_name = str_replace('mentions.mentions_type.', '', $config);
      $candidate_entitytypes[$mentions_name] = $mentions_name;
    }
    if (count($candidate_entitytypes) == 0) {
      return NULL;
    }
    $form['mentions_filter'] = [
      '#type' => 'checkboxes',
      '#options' => $candidate_entitytypes,
      '#default_value' => $this->settings['mentions_filter'],
      '#title' => $this
        ->t('Mentions types'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function setTextFormat($text_format) {
    $this->textFormat = $text_format;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FilterBase::$provider public property The name of the provider that owns this filter.
FilterBase::$settings public property An associative array containing the configured settings of this filter.
FilterBase::$status public property A Boolean indicating whether this filter is enabled.
FilterBase::$weight public property The weight of this filter compared to others in a filter collection.
FilterBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
FilterBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
FilterBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
FilterBase::getDescription public function Returns the administrative description for this filter plugin. Overrides FilterInterface::getDescription
FilterBase::getHTMLRestrictions public function Returns HTML allowed by this filter's configuration. Overrides FilterInterface::getHTMLRestrictions 4
FilterBase::getLabel public function Returns the administrative label for this filter plugin. Overrides FilterInterface::getLabel
FilterBase::getType public function Returns the processing type of this filter plugin. Overrides FilterInterface::getType
FilterBase::prepare public function Prepares the text for processing. Overrides FilterInterface::prepare
FilterBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
FilterBase::tips public function Generates a filter's tip. Overrides FilterInterface::tips 9
FilterInterface::TYPE_HTML_RESTRICTOR constant HTML tag and attribute restricting filters to prevent XSS attacks.
FilterInterface::TYPE_MARKUP_LANGUAGE constant Non-HTML markup language filters that generate HTML.
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE constant Irreversible transformation filters.
FilterInterface::TYPE_TRANSFORM_REVERSIBLE constant Reversible transformation filters.
MentionsFilter::$config protected property
MentionsFilter::$entityManager protected property
MentionsFilter::$entityQueryService private property
MentionsFilter::$inputSettings private property
MentionsFilter::$mentionsManager protected property
MentionsFilter::$mentionTypes private property
MentionsFilter::$outputSettings private property
MentionsFilter::$renderer protected property
MentionsFilter::$textFormat private property
MentionsFilter::$tokenService private property
MentionsFilter::checkMentionTypes public function Checks if there are mentionTypes.
MentionsFilter::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
MentionsFilter::filterMentions public function Filters mentions in a text.
MentionsFilter::getMentions public function Gets the mentions in text.
MentionsFilter::getSettings public function Returns the settings.
MentionsFilter::process public function Performs the filter processing. Overrides FilterInterface::process
MentionsFilter::setTextFormat public function
MentionsFilter::settingsForm public function Generates a filter's settings form. Overrides FilterBase::settingsForm
MentionsFilter::shouldApplyFilter public function Checks if a textFormat filter should be applied.
MentionsFilter::__construct public function MentionsFilter constructor. Overrides FilterBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.