You are here

class SearchExcludeNodeSearch in Search Exclude (Node) 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/Search/SearchExcludeNodeSearch.php \Drupal\search_exclude\Plugin\Search\SearchExcludeNodeSearch
  2. 2.0.x src/Plugin/Search/SearchExcludeNodeSearch.php \Drupal\search_exclude\Plugin\Search\SearchExcludeNodeSearch

Search plugin to exclude node bundles from the Search module index.

Plugin annotation


@SearchPlugin(
  id = "search_exclude_node_search",
  title = @Translation("Content (Exclude)")
)

Hierarchy

Expanded class hierarchy of SearchExcludeNodeSearch

1 file declares its use of SearchExcludeNodeSearch
search_exclude.module in ./search_exclude.module

File

src/Plugin/Search/SearchExcludeNodeSearch.php, line 19

Namespace

Drupal\search_exclude\Plugin\Search
View source
class SearchExcludeNodeSearch extends NodeSearch {

  /**
   * {@inheritdoc}
   */
  public function updateIndex() {

    // Interpret the cron limit setting as the maximum number of nodes to index
    // per cron run.
    $limit = (int) $this->searchSettings
      ->get('index.cron_limit');
    $query = $this->database
      ->select('node', 'n', array(
      'target' => 'replica',
    ));
    $query
      ->addField('n', 'nid');
    $query
      ->leftJoin('search_dataset', 'sd', 'sd.sid = n.nid AND sd.type = :type', array(
      ':type' => $this
        ->getPluginId(),
    ));
    $query
      ->addExpression('CASE MAX(sd.reindex) WHEN NULL THEN 0 ELSE 1 END', 'ex');
    $query
      ->addExpression('MAX(sd.reindex)', 'ex2');
    if (!empty($this->configuration['excluded_bundles'])) {
      $query
        ->condition('n.type', $this->configuration['excluded_bundles'], 'NOT IN');
    }
    $query
      ->condition($query
      ->orConditionGroup()
      ->where('sd.sid IS NULL')
      ->condition('sd.reindex', 0, '<>'));
    $query
      ->orderBy('ex', 'DESC')
      ->orderBy('ex2')
      ->orderBy('n.nid')
      ->groupBy('n.nid')
      ->range(0, $limit);
    $nids = $query
      ->execute()
      ->fetchCol();
    if (!$nids) {
      return;
    }
    $node_storage = $this->entityTypeManager
      ->getStorage('node');
    $words = [];
    try {
      foreach ($node_storage
        ->loadMultiple($nids) as $node) {
        $words += $this
          ->indexNode($node);
      }
    } finally {
      if (isset($this->searchIndex)) {
        $this->searchIndex
          ->updateWordWeights($words);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function indexStatus() {
    if (!count($this->configuration['excluded_bundles'])) {
      return parent::indexStatus();
    }
    $total = $this->database
      ->query('SELECT COUNT(*) FROM {node} WHERE type NOT IN (:excluded_bundles[])', array(
      ':excluded_bundles[]' => $this->configuration['excluded_bundles'],
    ))
      ->fetchField();
    $remaining = $this->database
      ->query("SELECT COUNT(DISTINCT n.nid) FROM {node} n LEFT JOIN {search_dataset} sd ON sd.sid = n.nid AND sd.type = :type WHERE (sd.sid IS NULL OR sd.reindex <> 0) AND n.type NOT IN (:excluded_bundles[])", array(
      ':type' => $this
        ->getPluginId(),
      ':excluded_bundles[]' => $this->configuration['excluded_bundles'],
    ))
      ->fetchField();
    return array(
      'remaining' => $remaining,
      'total' => $total,
    );
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $configuration = parent::defaultConfiguration();
    $configuration['excluded_bundles'] = [];
    return $configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function searchFormAlter(array &$form, FormStateInterface $form_state) {
    parent::searchFormAlter($form, $form_state);

    // Remove excluded bundles from search form.
    $options = $form['advanced']['types-fieldset']['type']['#options'];
    $bundles = array_diff_key($options, $this->configuration['excluded_bundles']);
    $form['advanced']['types-fieldset']['type']['#options'] = $bundles;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    // Get node bundles.
    $bundles = array_map(array(
      '\\Drupal\\Component\\Utility\\Html',
      'escape',
    ), node_type_get_names());

    // Only show the form if we have node bundles.
    if (!count($bundles)) {
      return $form;
    }
    $form['exclude_bundles'] = [
      '#type' => 'details',
      '#title' => t('Exclude content types'),
      '#open' => TRUE,
    ];
    $form['exclude_bundles']['info'] = [
      '#markup' => '<p><em>' . $this
        ->t('Select the content types to exclude from the search index.') . '</em></p>',
    ];
    $form['exclude_bundles']['excluded_bundles'] = [
      '#type' => 'checkboxes',
      '#options' => $bundles,
      '#default_value' => $this->configuration['excluded_bundles'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['excluded_bundles'] = array_filter($form_state
      ->getValue('excluded_bundles'));
    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * Check if the entity needs to be re-indexed.
   *
   * If the $entity is a comment, the reindexing will aply to the associated
   * node, otherwise the node itself. This will trigger a re-indexing only if
   * the node type is not configured to be excluded by this plugin.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   Either a node or a comments entity.
   */
  public function reIndex(EntityInterface $entity) {
    if ($entity instanceof CommentInterface) {
      if ($entity
        ->getCommentedEntityTypeId() !== 'node') {
        return;
      }
      $node = $entity
        ->getCommentedEntity();
    }
    else {
      if ($entity instanceof NodeInterface) {
        $node = $entity;
      }
      else {
        return;
      }
    }

    /** @var \Drupal\node\NodeInterface $node */
    if (in_array($node
      ->getType(), $this->configuration['excluded_bundles'])) {
      return;
    }

    /** @var \Drupal\search\SearchIndex $searchIndex */
    $search_index = \Drupal::service('search.index');
    $search_index
      ->markForReindex('search_exclude_node_search', $node
      ->id());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::getCacheContexts public function 4
CacheableDependencyTrait::getCacheMaxAge public function 4
CacheableDependencyTrait::getCacheTags public function 4
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
ConfigurableSearchPluginBase::$searchPageId protected property The unique ID for the search page using this plugin.
ConfigurableSearchPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ConfigurableSearchPluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ConfigurableSearchPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ConfigurableSearchPluginBase::setSearchPageId public function Sets the ID for the search page using this plugin. Overrides ConfigurableSearchPluginInterface::setSearchPageId
ConfigurableSearchPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
NodeSearch::$account protected property The Drupal account to use for checking for access to advanced search.
NodeSearch::$advanced protected property The list of options and info for advanced search filters.
NodeSearch::$database protected property The current database connection.
NodeSearch::$databaseReplica protected property The replica database connection.
NodeSearch::$entityTypeManager protected property The entity type manager.
NodeSearch::$languageManager protected property The language manager.
NodeSearch::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
NodeSearch::$moduleHandler protected property A module manager object.
NodeSearch::$rankings protected property An array of additional rankings from hook_ranking().
NodeSearch::$renderer protected property The Renderer service to format the username and node.
NodeSearch::$searchIndex protected property The search index.
NodeSearch::$searchSettings protected property A config object for 'search.settings'.
NodeSearch::access public function Checks data value access. Overrides AccessibleInterface::access
NodeSearch::addNodeRankings protected function Adds the configured rankings to the search query.
NodeSearch::ADVANCED_FORM constant A constant for setting and checking the query string.
NodeSearch::buildSearchUrlQuery public function Builds the URL GET query parameters array for search. Overrides SearchPluginBase::buildSearchUrlQuery
NodeSearch::create public static function Creates an instance of the plugin. Overrides SearchPluginBase::create
NodeSearch::execute public function Executes the search. Overrides SearchInterface::execute
NodeSearch::findResults protected function Queries to find search results, and sets status messages.
NodeSearch::getRankings protected function Gathers ranking definitions from hook_ranking().
NodeSearch::getType public function Returns the search index type this plugin uses. Overrides SearchPluginBase::getType
NodeSearch::indexClear public function Clears the search index for this plugin. Overrides SearchIndexingInterface::indexClear
NodeSearch::indexNode protected function Indexes a single node.
NodeSearch::isSearchExecutable public function Verifies if the values set via setSearch() are valid and sufficient. Overrides SearchPluginBase::isSearchExecutable
NodeSearch::markForReindex public function Marks the search index for reindexing for this plugin. Overrides SearchIndexingInterface::markForReindex
NodeSearch::parseAdvancedDefaults protected function Parses the advanced search form default values.
NodeSearch::prepareResults protected function Prepares search results for rendering.
NodeSearch::removeSubmittedInfo public function Removes the submitted by information from the build array.
NodeSearch::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
NodeSearch::__construct public function Constructs a \Drupal\node\Plugin\Search\NodeSearch object. Overrides ConfigurableSearchPluginBase::__construct
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 2
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.
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SearchExcludeNodeSearch::buildConfigurationForm public function Form constructor. Overrides NodeSearch::buildConfigurationForm
SearchExcludeNodeSearch::defaultConfiguration public function Gets default configuration for this plugin. Overrides NodeSearch::defaultConfiguration
SearchExcludeNodeSearch::indexStatus public function Reports the status of indexing. Overrides NodeSearch::indexStatus
SearchExcludeNodeSearch::reIndex public function Check if the entity needs to be re-indexed.
SearchExcludeNodeSearch::searchFormAlter public function Alters the search form when being built for a given plugin. Overrides NodeSearch::searchFormAlter
SearchExcludeNodeSearch::submitConfigurationForm public function Form submission handler. Overrides NodeSearch::submitConfigurationForm
SearchExcludeNodeSearch::updateIndex public function Updates the search index for this plugin. Overrides NodeSearch::updateIndex
SearchPluginBase::$keywords protected property The keywords to use in a search.
SearchPluginBase::$searchAttributes protected property Array of attributes - usually from the request object.
SearchPluginBase::$searchParameters protected property Array of parameters from the query string from the request.
SearchPluginBase::buildResults public function Executes the search and builds render arrays for the result items. Overrides SearchInterface::buildResults 1
SearchPluginBase::getAttributes public function Returns the currently set attributes (from the request). Overrides SearchInterface::getAttributes
SearchPluginBase::getHelp public function Returns the searching help. Overrides SearchInterface::getHelp 1
SearchPluginBase::getKeywords public function Returns the currently set keywords of the plugin instance. Overrides SearchInterface::getKeywords
SearchPluginBase::getParameters public function Returns the current parameters set using setSearch(). Overrides SearchInterface::getParameters
SearchPluginBase::setSearch public function Sets the keywords, parameters, and attributes to be used by execute(). Overrides SearchInterface::setSearch 1
SearchPluginBase::suggestedTitle public function Provides a suggested title for a page of search results. Overrides SearchInterface::suggestedTitle
SearchPluginBase::usesAdminTheme public function Returns whether or not search results should be displayed in admin theme. Overrides SearchInterface::usesAdminTheme
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
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.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.