You are here

class TestBackend in Search API 8

Provides a dummy backend for testing purposes.

Plugin annotation


@SearchApiBackend(
  id = "search_api_test",
  label = @Translation("Test backend"),
  description = @Translation("Dummy backend implementation")
)

Hierarchy

Expanded class hierarchy of TestBackend

1 file declares its use of TestBackend
BackendPluginBaseTest.php in tests/src/Unit/BackendPluginBaseTest.php

File

tests/search_api_test/src/Plugin/search_api/backend/TestBackend.php, line 23

Namespace

Drupal\search_api_test\Plugin\search_api\backend
View source
class TestBackend extends BackendPluginBase implements PluginFormInterface {
  use PluginFormTrait;
  use TestPluginTrait {
    checkError as traitCheckError;
  }

  /**
   * {@inheritdoc}
   */
  public function postInsert() {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function preUpdate() {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function postUpdate() {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      return call_user_func($override, $this);
    }
    $this
      ->checkError(__FUNCTION__);
    return $this
      ->getReturnValue(__FUNCTION__, FALSE);
  }

  /**
   * {@inheritdoc}
   */
  public function viewSettings() {
    return [
      [
        'label' => 'Dummy Info',
        'info' => 'Dummy Value',
        'status' => 'error',
      ],
      [
        'label' => 'Dummy Info 2',
        'info' => 'Dummy Value 2',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getSupportedFeatures() {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      return call_user_func($override, $this);
    }
    return [
      'search_api_mlt',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function supportsDataType($type) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      return call_user_func($override, $this, $type);
    }
    return in_array($type, [
      'search_api_test',
      'search_api_test_altering',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'test' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['test'] = [
      '#type' => 'textfield',
      '#title' => 'Test',
      '#default_value' => $this->configuration['test'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function indexItems(IndexInterface $index, array $items) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      return call_user_func($override, $this, $index, $items);
    }
    $this
      ->checkError(__FUNCTION__);
    $state = \Drupal::state();
    $key = 'search_api_test.backend.indexed.' . $index
      ->id();
    $indexed_values = $state
      ->get($key, []);
    $skip = $state
      ->get('search_api_test.backend.indexItems.skip', []);
    $skip = array_flip($skip);

    /** @var \Drupal\search_api\Item\ItemInterface $item */
    foreach ($items as $id => $item) {
      if (isset($skip[$id])) {
        unset($items[$id]);
        continue;
      }
      $indexed_values[$id] = [];
      foreach ($item
        ->getFields() as $field_id => $field) {
        $indexed_values[$id][$field_id] = $field
          ->getValues();
      }
    }
    $state
      ->set($key, $indexed_values);
    return array_keys($items);
  }

  /**
   * {@inheritdoc}
   */
  public function addIndex(IndexInterface $index) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this, $index);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function updateIndex(IndexInterface $index) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this, $index);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
    $index
      ->reindex();
  }

  /**
   * {@inheritdoc}
   */
  public function removeIndex($index) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this, $index);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteItems(IndexInterface $index, array $item_ids) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this, $index, $item_ids);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
    $state = \Drupal::state();
    $key = 'search_api_test.backend.indexed.' . $index
      ->id();
    $indexed_values = $state
      ->get($key, []);

    /** @var \Drupal\search_api\Item\ItemInterface $item */
    foreach ($item_ids as $item_id) {
      unset($indexed_values[$item_id]);
    }
    $state
      ->set($key, $indexed_values);
  }

  /**
   * {@inheritdoc}
   */
  public function deleteAllIndexItems(IndexInterface $index, $datasource_id = NULL) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this, $index, $datasource_id);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
    $key = 'search_api_test.backend.indexed.' . $index
      ->id();
    if (!$datasource_id) {
      \Drupal::state()
        ->delete($key);
      return;
    }
    $indexed = \Drupal::state()
      ->get($key, []);

    /** @var \Drupal\search_api\Item\ItemInterface $item */
    foreach (array_keys($indexed) as $item_id) {
      list($item_datasource_id) = Utility::splitCombinedId($item_id);
      if ($item_datasource_id == $datasource_id) {
        unset($indexed[$item_id]);
      }
    }
    \Drupal::state()
      ->set($key, $indexed);
  }

  /**
   * {@inheritdoc}
   */
  public function search(QueryInterface $query) {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      call_user_func($override, $this, $query);
      return;
    }
    $this
      ->checkError(__FUNCTION__);
    $results = $query
      ->getResults();
    $result_items = [];
    $datasources = $query
      ->getIndex()
      ->getDatasources();

    /** @var \Drupal\search_api\Datasource\DatasourceInterface $datasource */
    $datasource = reset($datasources);
    $datasource_id = $datasource
      ->getPluginId();
    $fields_helper = \Drupal::getContainer()
      ->get('search_api.fields_helper');
    if ($query
      ->getKeys() && $query
      ->getKeys()[0] == 'test') {
      $item_id = Utility::createCombinedId($datasource_id, '1');
      $item = $fields_helper
        ->createItem($query
        ->getIndex(), $item_id, $datasource);
      $item
        ->setScore(2);
      $item
        ->setExcerpt('test');
      $result_items[$item_id] = $item;
    }
    elseif ($query
      ->getOption('search_api_mlt')) {
      $item_id = Utility::createCombinedId($datasource_id, '2');
      $item = $fields_helper
        ->createItem($query
        ->getIndex(), $item_id, $datasource);
      $item
        ->setScore(2);
      $item
        ->setExcerpt('test test');
      $result_items[$item_id] = $item;
    }
    else {
      $item_id = Utility::createCombinedId($datasource_id, '1');
      $item = $fields_helper
        ->createItem($query
        ->getIndex(), $item_id, $datasource);
      $item
        ->setScore(1);
      $result_items[$item_id] = $item;
      $item_id = Utility::createCombinedId($datasource_id, '2');
      $item = $fields_helper
        ->createItem($query
        ->getIndex(), $item_id, $datasource);
      $item
        ->setScore(1);
      $result_items[$item_id] = $item;
    }
    $results
      ->setResultItems($result_items);
    $results
      ->setResultCount(count($result_items));
  }

  /**
   * {@inheritdoc}
   */
  public function isAvailable() {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {
      return call_user_func($override, $this);
    }
    return $this
      ->getReturnValue(__FUNCTION__, TRUE);
  }

  /**
   * {@inheritdoc}
   */
  public function getDiscouragedProcessors() {
    if ($override = $this
      ->getMethodOverride(__FUNCTION__)) {

      // Safeguard against "stupid" dummy methods used in tests, such as
      // \Drupal\search_api_test\MethodOverrides::overrideTestBackendMethod().
      $ret = call_user_func($override, $this);
      return is_array($ret) ? $ret : [];
    }
    return $this
      ->getReturnValue(__FUNCTION__, []);
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return $this->configuration['dependencies'] ?? [];
  }

  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {
    $remove = $this
      ->getReturnValue(__FUNCTION__, FALSE);
    if ($remove) {
      unset($this->configuration['dependencies']);
    }
    return $remove;
  }

  /**
   * {@inheritdoc}
   */
  protected function checkError($method) {
    $this
      ->traitCheckError($method);
    $this
      ->logMethodCall($method);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BackendPluginBase::$fieldsHelper protected property The fields helper.
BackendPluginBase::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
BackendPluginBase::$server protected property The server this backend is configured for.
BackendPluginBase::$serverId protected property The backend's server's ID.
BackendPluginBase::create public static function Creates an instance of the plugin. Overrides ConfigurablePluginBase::create 1
BackendPluginBase::getBackendDefinedFields public function Provides information on additional fields made available by the backend. Overrides BackendSpecificInterface::getBackendDefinedFields
BackendPluginBase::getFieldsHelper public function Retrieves the fields helper.
BackendPluginBase::getMessenger public function Retrieves the messenger.
BackendPluginBase::getQueryFulltextFields protected function Retrieves the effective fulltext fields from the query.
BackendPluginBase::getServer public function Retrieves the server entity for this backend. Overrides BackendInterface::getServer
BackendPluginBase::getSpecialFields protected function Creates dummy field objects for the "magic" fields present for every index. 1
BackendPluginBase::preDelete public function Notifies the backend that the server is about to be deleted. Overrides BackendInterface::preDelete 1
BackendPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginBase::setConfiguration
BackendPluginBase::setFieldsHelper public function Sets the fields helper.
BackendPluginBase::setMessenger public function Sets the messenger. Overrides MessengerTrait::setMessenger
BackendPluginBase::setServer public function Sets the server entity for this backend. Overrides BackendInterface::setServer
BackendPluginBase::validateOperator protected function Verifies that the given condition operator is valid for this backend.
BackendPluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides ConfigurablePluginBase::__construct 1
BackendPluginBase::__sleep public function Implements the magic __sleep() method. Overrides DependencySerializationTrait::__sleep 1
BackendPluginBase::__wakeup public function Implements the magic __wakeup() method. Overrides DependencySerializationTrait::__wakeup 1
ConfigurablePluginBase::calculatePluginDependencies Deprecated protected function Calculates and adds dependencies of a specific plugin instance.
ConfigurablePluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ConfigurablePluginBase::getDescription public function Returns the plugin's description. Overrides ConfigurablePluginInterface::getDescription
ConfigurablePluginBase::getPluginDependencies Deprecated protected function Calculates and returns dependencies of a specific plugin instance.
ConfigurablePluginBase::label public function Returns the label for use on the administration pages. Overrides ConfigurablePluginInterface::label
ConfigurablePluginBase::moduleHandler Deprecated protected function Wraps the module handler.
ConfigurablePluginBase::themeHandler Deprecated protected function Wraps the theme handler.
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.
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
HideablePluginBase::isHidden public function Determines whether this plugin should be hidden in the UI. Overrides HideablePluginInterface::isHidden 1
LoggerTrait::$logger protected property The logging channel to use.
LoggerTrait::getLogger public function Retrieves the logger.
LoggerTrait::logException protected function Logs an exception.
LoggerTrait::setLogger public function Sets the logger.
MessengerTrait::messenger public function Gets the messenger. 29
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.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. Aliased as: traitCalculatePluginDependencies 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance. Aliased as: traitGetPluginDependencies
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. Aliased as: traitModuleHandler 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. Aliased as: traitThemeHandler 1
PluginFormTrait::submitConfigurationForm public function Form submission handler. 7
PluginFormTrait::validateConfigurationForm public function Form validation handler. 2
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.
TestBackend::addIndex public function Adds a new index to this server. Overrides BackendPluginBase::addIndex
TestBackend::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
TestBackend::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides ConfigurablePluginBase::calculateDependencies
TestBackend::checkError protected function
TestBackend::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurablePluginBase::defaultConfiguration
TestBackend::deleteAllIndexItems public function Deletes all the items from the index. Overrides BackendSpecificInterface::deleteAllIndexItems
TestBackend::deleteItems public function Deletes the specified items from the index. Overrides BackendSpecificInterface::deleteItems
TestBackend::getDiscouragedProcessors public function Limits the processors displayed in the UI for indexes on this server. Overrides BackendPluginBase::getDiscouragedProcessors
TestBackend::getSupportedFeatures public function Returns all features that this backend supports. Overrides BackendPluginBase::getSupportedFeatures
TestBackend::indexItems public function Indexes the specified items. Overrides BackendSpecificInterface::indexItems
TestBackend::isAvailable public function Returns a boolean with the availability of the backend. Overrides BackendPluginBase::isAvailable
TestBackend::onDependencyRemoval public function Informs the plugin that some of its dependencies are being removed. Overrides ConfigurablePluginBase::onDependencyRemoval
TestBackend::postInsert public function Reacts to the server's creation. Overrides BackendPluginBase::postInsert
TestBackend::postUpdate public function Notifies the backend that its configuration was updated. Overrides BackendPluginBase::postUpdate
TestBackend::preUpdate public function Notifies the backend that its configuration is about to be updated. Overrides BackendPluginBase::preUpdate
TestBackend::removeIndex public function Removes an index from this server. Overrides BackendPluginBase::removeIndex
TestBackend::search public function Executes a search on this server. Overrides BackendSpecificInterface::search
TestBackend::supportsDataType public function Determines whether the backend supports a given add-on data type. Overrides BackendPluginBase::supportsDataType
TestBackend::updateIndex public function Notifies the server that an index attached to it has been changed. Overrides BackendPluginBase::updateIndex
TestBackend::viewSettings public function Returns additional, backend-specific information about this server. Overrides BackendPluginBase::viewSettings
TestPluginTrait::$pluginType protected property This object's plugin type.
TestPluginTrait::checkError protected function Throws an exception if set in the Drupal state for the given method. Aliased as: traitCheckError
TestPluginTrait::getMethodOverride protected function Retrieves a possible override set for the given method.
TestPluginTrait::getPluginType protected function Returns the plugin type of this object.
TestPluginTrait::getReturnValue protected function Retrieves the value to return for a certain method.
TestPluginTrait::logMethodCall protected function Logs a method call to the site state.
TestPluginTrait::__call public function Implements the magic __call() method.