/** * {@inheritdoc} */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { parent::buildOptionsForm($form, $form_state); unset($form['break_phrase']); unset($form['not']); $index = Index::load(substr($this->table, 17)); $fields = array(); foreach ($index->getFields() as $key => $field) { $fields[$key] = $field->getLabel(); } if ($fields) { $form['fields'] = array( '#type' => 'select', '#title' => $this->t('Fields for similarity'), '#description' => $this->t('Select the fields that will be used for finding similar content. If no fields are selected, all available fields will be used.'), '#options' => $fields, '#size' => min(8, count($fields)), '#multiple' => TRUE, '#default_value' => $this->options['fields'], ); } else { $form['fields'] = array( '#type' => 'value', '#value' => array(), ); } }
public function page(Request $request, $search_api_page, $keyword = '') { $build = array(); /** @var $searchApiPage SearchApiPageInterface */ $searchApiPage = SearchApiPage::load($search_api_page); // Page title. $build['#title'] = $searchApiPage->label(); /** @var $searchApiIndex IndexInterface */ $searchApiIndex = Index::load($searchApiPage->getIndex()); // Create the query. $query = $searchApiIndex->query(['parse_mode' => 'direct', 'limit' => $searchApiPage->getLimit(), 'offset' => !is_null($request->get('page')) ? $request->get('page') : 0, 'search id' => 'search_api_page:' . $searchApiPage->id()]); // Keywords. if (!empty($keyword)) { $query->keys($keyword); } // Index fields. $query->setFulltextFields(array('rendered_item')); $result = $query->execute(); $items = $result->getResultItems(); /** @var $item ItemInterface*/ $results = array(); foreach ($items as $item) { list(, $path, $langcode) = explode(':', $item->getId()); list($entity_type, $id) = explode('/', $path); $entity = $this->entityManager()->getStorage($entity_type)->load($id); $results[] = $this->entityManager()->getViewBuilder($entity_type)->view($entity, 'teaser'); } if (!empty($results)) { $build['results'] = $results; // Build pager. pager_default_initialize($result->getResultCount(), $searchApiPage->getLimit()); $build['pager'] = array('#type' => 'pager'); } return $build; }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->setUpExampleStructure(); Utility::getIndexTaskManager()->addItemsAll(Index::load($this->indexId)); }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->installSchema('search_api', array('search_api_item', 'search_api_task')); $this->installSchema('system', array('router')); $this->installSchema('user', array('users_data')); $this->setUpExampleStructure(); $this->installConfig(array('search_api_test_db')); $this->insertExampleContent(); // Create a test server. $this->server = Server::create(array( 'name' => $this->randomString(), 'id' => $this->randomMachineName(), 'status' => 1, 'backend' => 'search_api_test_backend', )); $this->server->save(); $this->index = Index::load('database_search_index'); $this->index->setServer($this->server); }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->setUpExampleStructure(); \Drupal::getContainer()->get('search_api.index_task_manager')->addItemsAll(Index::load($this->indexId)); $this->insertExampleContent(); $this->indexItems($this->indexId); }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); // Add a test server and index. $this->getTestServer(); $this->getTestIndex(); // Set up example structure and content and populate the test index with // that content. $this->setUpExampleStructure(); $this->insertExampleContent(); \Drupal::getContainer()->get('search_api.index_task_manager')->addItemsAll(Index::load($this->indexId)); $this->indexItems($this->indexId); }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); /* @var $search_api_page \Drupal\search_api_page\SearchApiPageInterface */ $search_api_page = $this->entity; $form['label'] = array('#type' => 'textfield', '#title' => $this->t('Title'), '#maxlength' => 255, '#default_value' => $search_api_page->label(), '#required' => TRUE, '#description' => $this->t('This will also be used as the page title.')); $form['id'] = array('#type' => 'machine_name', '#default_value' => $search_api_page->id(), '#machine_name' => array('exists' => '\\Drupal\\search_api_page\\Entity\\SearchApiPage::load'), '#disabled' => !$search_api_page->isNew()); // Default index and states. $default_index = $search_api_page->getIndex(); $default_index_states = array('visible' => array(':input[name="index"]' => array('value' => $default_index))); $index_options = array(); $search_api_indexes = $this->entityTypeManager->getStorage('search_api_index')->loadMultiple(); /* @var $search_api_index \Drupal\search_api\IndexInterface */ foreach ($search_api_indexes as $search_api_index) { $index_options[$search_api_index->id()] = $search_api_index->label(); } $form['index_fieldset'] = array('#type' => 'fieldset', '#title' => $this->t('Index')); $form['index_fieldset']['index'] = array('#type' => 'select', '#title' => $this->t('Search API index'), '#options' => $index_options, '#default_value' => $default_index, '#required' => TRUE); $form['index_fieldset']['previous_index'] = array('#type' => 'value', '#value' => $default_index); $searched_fields = $search_api_page->getFullTextFields(); $form['index_fieldset']['searched_fields'] = array('#type' => 'select', '#multiple' => TRUE, '#options' => $searched_fields, '#size' => min(4, count($searched_fields)), '#title' => $this->t('Searched fields'), '#description' => $this->t('Select the fields that will be searched. If no fields are selected, all available fulltext fields will be searched.'), '#default_value' => $search_api_page->getSearchedFields(), '#access' => !empty($default_index), '#states' => $default_index_states); $form['page_fieldset'] = array('#type' => 'fieldset', '#title' => $this->t('Page'), '#states' => array('visible' => array(':input[name="index"]' => array('value' => $default_index))), '#access' => !empty($default_index)); $form['page_fieldset']['path'] = array('#type' => 'textfield', '#title' => $this->t('Path'), '#maxlength' => 255, '#default_value' => $search_api_page->getPath(), '#description' => $this->t("Do not include a trailing slash."), '#required' => TRUE, '#access' => !empty($default_index), '#states' => $default_index_states); $form['page_fieldset']['previous_path'] = array('#type' => 'value', '#value' => $search_api_page->getPath(), '#access' => !empty($default_index)); $form['page_fieldset']['clean_url'] = array('#type' => 'checkbox', '#title' => $this->t('Use clean URL\'s'), '#default_value' => $search_api_page->getCleanUrl(), '#access' => !empty($default_index), '#states' => $default_index_states); $form['page_fieldset']['previous_clean_url'] = array('#type' => 'value', '#default_value' => $search_api_page->getCleanUrl()); $form['page_fieldset']['limit'] = array('#type' => 'number', '#title' => $this->t('Limit'), '#default_value' => $search_api_page->getLimit(), '#min' => 1, '#required' => TRUE, '#access' => !empty($default_index), '#states' => $default_index_states); $form['page_fieldset']['show_search_form'] = array('#type' => 'checkbox', '#title' => $this->t('Show search form above results'), '#default_value' => $search_api_page->showSearchForm(), '#access' => !empty($default_index), '#states' => $default_index_states); $form['page_fieldset']['show_all_when_no_keys'] = array('#type' => 'checkbox', '#title' => $this->t('Show all results when no search is performed'), '#default_value' => $search_api_page->showAllResultsWhenNoSearchIsPerformed(), '#access' => !empty($default_index), '#states' => $default_index_states); $form['page_fieldset']['style'] = array('#type' => 'radios', '#title' => $this->t('Style'), '#options' => array('view_modes' => $this->t('View modes'), 'search_results' => $this->t('Search results')), '#default_value' => $search_api_page->getStyle(), '#required' => TRUE, '#access' => !empty($default_index), '#states' => $default_index_states); if (!empty($default_index)) { $form['view_mode_configuration'] = array('#type' => 'fieldset', '#tree' => TRUE, '#title' => $this->t('View modes'), '#states' => array('visible' => array(':input[name="style"]' => array('value' => 'view_modes'), ':input[name="index"]' => array('value' => $default_index)))); /* @var $index \Drupal\search_api\IndexInterface */ $index = Index::load($search_api_page->getIndex()); $view_mode_configuration = $search_api_page->getViewModeConfiguration(); foreach ($index->getDatasources() as $datasource_id => $datasource) { $bundles = $datasource->getBundles(); foreach ($bundles as $bundle_id => $bundle_label) { $view_modes = $datasource->getViewModes($bundle_id); $form['view_mode_configuration'][$datasource_id . '_' . $bundle_id] = array('#type' => 'select', '#title' => $this->t('View mode for %datasource » %bundle', array('%datasource' => $datasource->label(), '%bundle' => $bundle_label)), '#options' => $view_modes); if (isset($view_mode_configuration[$datasource_id . '_' . $bundle_id])) { $form['view_mode_configuration'][$datasource_id . '_' . $bundle_id]['#default_value'] = $view_mode_configuration[$datasource_id . '_' . $bundle_id]; } } } } return $form; }
/** * {@inheritdoc} */ public function fillFacetsWithResults($facets) { // Check if there are results in the static cache. $results = $this->searchApiResultsCache->getResults($this->pluginId); // If there are no results, execute the search page and check for results // again. This happens when a page or block is cached, so Search API has // not fired an actual search. if (!$results) { list(, $search_api_page) = explode(':', $this->pluginId); /* @var $search_api_page \Drupal\search_api_page\SearchApiPageInterface */ $search_api_page = SearchApiPageEntity::load($search_api_page); /* @var $search_api_index \Drupal\search_api\IndexInterface */ $search_api_index = Index::load($search_api_page->getIndex()); // Create the query. $query = $search_api_index->query(['parse_mode' => 'direct', 'limit' => $search_api_page->getLimit(), 'offset' => isset($_GET['page']) ? $_GET['page'] : 0, 'search id' => 'search_api_page:' . $search_api_page->id()]); // Keys. $keys = \Drupal::request()->get('keys'); if (!empty($keys)) { $query->keys($keys); } // Index fields. $query->setFulltextFields($search_api_page->getSearchedFields()); // Execute the query. $results = $query->execute(); } // If we got results from the cache, this is the first code executed in this // method, so it's good to double check that we can actually work with // $results. if ($results instanceof ResultSetInterface) { // Get our facet data from the results. $facet_results = $results->getExtraData('search_api_facets'); // Loop over each facet and execute the build method from the given query // type. foreach ($facets as $facet) { if (isset($facet_results[$facet->getFieldIdentifier()])) { $configuration = array('query' => NULL, 'facet' => $facet, 'results' => $facet_results[$facet->getFieldIdentifier()]); // Get the Facet Specific Query Type so we can process the results // using the build() function of the query type. $query_type = $this->queryTypePluginManager->createInstance($facet->getQueryType(), $configuration); $query_type->build(); } } } }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->installSchema('search_api', array('search_api_item', 'search_api_task')); $this->installSchema('system', array('router')); $this->installSchema('user', array('users_data')); $this->installEntitySchema('entity_test'); // Do not use a batch for tracking the initial items after creating an // index when running the tests via the GUI. Otherwise, it seems Drupal's // Batch API gets confused and the test fails. \Drupal::state()->set('search_api_use_tracking_batch', FALSE); $this->installConfig(array('search_api_test_db')); // Create test entities. $this->entities[1] = EntityTest::create(array('name' => 'foo bar baz föö smile' . json_decode('"\\u1F601"'), 'body' => 'test test case Case casE', 'type' => 'item', 'keywords' => array('Orange', 'orange', 'örange', 'Orange'), 'category' => 'item_category')); $this->entities[2] = EntityTest::create(array('name' => 'foo bar baz föö smile', 'body' => 'test test case Case casE', 'type' => 'item', 'keywords' => array('strawberry', 'llama'), 'category' => 'item_category')); $this->entities[1]->save(); $this->entities[2]->save(); // Create a test server. $this->server = Server::create(array('name' => 'Server test ~', 'id' => 'test', 'status' => 1, 'backend' => 'search_api_test_backend')); $this->server->save(); $this->index = Index::load('database_search_index'); $this->index->setServer($this->server); }
/** * Router callback. * * @param Request $request * The request. * @param string $search_api_page_name * The search api page name. * @param string $keys * The search word. * * @return array $build * The page build. */ public function page(Request $request, $search_api_page_name, $keys = '') { $build = array(); /* @var $search_api_page \Drupal\search_api_page\SearchApiPageInterface */ $search_api_page = SearchApiPage::load($search_api_page_name); // Keys can be in the query. if (!$search_api_page->getCleanUrl()) { $keys = $request->get('keys'); } // Page title. $build['#title'] = $search_api_page->label(); // Show the search form. if ($search_api_page->showSearchForm()) { $args = array('search_api_page' => $search_api_page->id(), 'keys' => $keys); $build['#form'] = $this->formBuilder()->getForm('Drupal\\search_api_page\\Form\\SearchApiPageBlockForm', $args); } $perform_search = TRUE; if (empty($keys) && !$search_api_page->showAllResultsWhenNoSearchIsPerformed()) { $perform_search = FALSE; } if ($perform_search) { /* @var $search_api_index \Drupal\search_api\IndexInterface */ $search_api_index = Index::load($search_api_page->getIndex()); // Create the query. $query = $search_api_index->query(['parse_mode' => 'direct', 'limit' => $search_api_page->getLimit(), 'offset' => !is_null($request->get('page')) ? $request->get('page') : 0, 'search id' => 'search_api_page:' . $search_api_page->id()]); // Search for keys. if (!empty($keys)) { $query->keys($keys); } // Index fields. $query->setFulltextFields($search_api_page->getSearchedFields()); $result = $query->execute(); $items = $result->getResultItems(); /* @var $item \Drupal\search_api\Item\ItemInterface*/ $results = array(); foreach ($items as $item) { list(, $path, $langcode) = explode(':', $item->getId()); list($entity_type, $id) = explode('/', $path); // Get the entity. $entity = $this->entityTypeManager()->getStorage($entity_type)->load($id); // Render as view modes. if ($search_api_page->renderAsViewModes()) { $key = 'entity:' . $entity_type . '_' . $entity->bundle(); $view_mode_configuration = $search_api_page->getViewModeConfiguration(); $view_mode = isset($view_mode_configuration[$key]) ? $view_mode_configuration[$key] : 'default'; $results[] = $this->entityTypeManager()->getViewBuilder($entity_type)->view($entity, $view_mode); } // Render as snippets. if ($search_api_page->renderAsSnippets()) { $results[] = array('#theme' => 'search_api_page_result', '#item' => $item, '#entity' => $entity); } } if (!empty($results)) { $build['#search_title'] = array('#markup' => $this->t('Search results')); $build['#no_of_results'] = array('#markup' => $this->formatPlural($result->getResultCount(), '1 result found', '@count results found')); $build['#results'] = $results; // Build pager. pager_default_initialize($result->getResultCount(), $search_api_page->getLimit()); $build['#pager'] = array('#type' => 'pager'); } elseif ($perform_search) { $build['#no_results_found'] = array('#markup' => $this->t('Your search yielded no results.')); $build['#search_help'] = array('#markup' => $this->t('<ul> <li>Check if your spelling is correct.</li> <li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>"bike shed"</em>.</li> <li>Consider loosening your query with <em>OR</em>. <em>bike OR shed</em> will often show more results than <em>bike shed</em>.</li> </ul>')); } } $build['#theme'] = 'search_api_page'; // TODO caching dependencies. return $build; }
/** * Tests whether the default search was correctly installed. */ protected function testDefaultSetupWorking() { $server = Server::load('default_server'); $this->assertTrue($server, 'Server can be loaded'); $index = Index::load('default_index'); $this->assertTrue($index, 'Index can be loaded'); $this->drupalGet('search/content'); $this->assertResponse(200, 'Anonymous user can access the search page.'); $this->drupalLogin($this->authenticatedUser); $this->drupalGet('search/content'); $this->assertResponse(200, 'Authenticated user can access the search page.'); }
/** * Creates or deletes an index. * * @param string $name * (optional) The name of the index. * @param string $id * (optional) The ID of the index. * @param string $server_id * (optional) The server to which the index should be attached. * @param string $datasource_id * (optional) The ID of a datasource to set for this index. * @param bool $reset * (optional) If TRUE, delete the index instead of creating it. (Only the * index's ID is required in that case.) * * @return \Drupal\search_api\IndexInterface * A search index. */ public function getTestIndex($name = 'WebTest Index', $id = 'webtest_index', $server_id = 'webtest_server', $datasource_id = 'entity:node', $reset = FALSE) { if ($reset) { $index = Index::load($id); if ($index) { $index->delete(); } } else { $index = Index::create(array( 'id' => $id, 'name' => $name, 'description' => $name, 'server' => $server_id, 'datasources' => array($datasource_id), )); $index->save(); } return $index; }
/** * Counts the number of tracked items in the test index. * * @return int * The number of tracked items in the test index. */ protected function countTrackedItems() { /** @var \Drupal\search_api\IndexInterface $index */ $index = Index::load($this->indexId); return $index->getTrackerInstance()->getTotalItemsCount(); }
/** * Tests whether the default search was correctly installed. */ protected function testInstallAndDefaultSetupWorking() { $this->drupalLogin($this->adminUser); // Install the search_api_db_defaults module. $edit_enable = array('modules[Search][search_api_db_defaults][enable]' => TRUE); $this->drupalPostForm('admin/modules', $edit_enable, t('Install')); $this->assertText(t('Some required modules must be enabled'), 'Dependencies required.'); $this->drupalPostForm(NULL, NULL, t('Continue')); $args = array('@count' => 3, '%names' => 'Database Search Defaults, Database search, Search API'); $success_text = strip_tags(t('@count modules have been enabled: %names.', $args)); $this->assertText($success_text, 'Modules have been installed.'); $this->rebuildContainer(); $server = Server::load('default_server'); $this->assertTrue($server, 'Server can be loaded'); $index = Index::load('default_index'); $this->assertTrue($index, 'Index can be loaded'); $this->drupalLogin($this->authenticatedUser); $this->drupalGet('search/content'); $this->assertResponse(200, 'Authenticated user can access the search view.'); $this->drupalLogin($this->adminUser); // Uninstall the module. $edit_disable = array('uninstall[search_api_db_defaults]' => TRUE); $this->drupalPostForm('admin/modules/uninstall', $edit_disable, t('Uninstall')); $this->drupalPostForm(NULL, array(), t('Uninstall')); $this->rebuildContainer(); $this->assertFalse($this->container->get('module_handler')->moduleExists('search_api_db_defaults'), 'Search API DB Defaults module uninstalled.'); // Check if the server is found in the Search API admin UI. $this->drupalGet('admin/config/search/search-api/server/default_server'); $this->assertResponse(200, 'Server was not removed.'); // Check if the index is found in the Search API admin UI. $this->drupalGet('admin/config/search/search-api/index/default_index'); $this->assertResponse(200, 'Index was not removed.'); $this->drupalLogin($this->authenticatedUser); $this->drupalGet('search/content'); $this->assertResponse(200, 'Authenticated user can access the search view.'); $this->drupalLogin($this->adminUser); // Enable the module again. This should fail because the either the index // or the server or the view was found. $this->drupalPostForm('admin/modules', $edit_enable, t('Install')); $this->assertText(t('It looks like the default setup provided by this module already exists on your site. Cannot re-install module.')); // Delete all the entities that we would fail on if they exist. $entities_to_remove = array('search_api_index' => 'default_index', 'search_api_server' => 'default_server', 'view' => 'search_content'); /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */ $entity_type_manager = \Drupal::service('entity_type.manager'); foreach ($entities_to_remove as $entity_type => $entity_id) { /** @var \Drupal\Core\Entity\EntityStorageInterface $entity_storage */ $entity_storage = $entity_type_manager->getStorage($entity_type); $entity_storage->resetCache(); $entities = $entity_storage->loadByProperties(array('id' => $entity_id)); if (!empty($entities[$entity_id])) { $entities[$entity_id]->delete(); } } // Delete the article content type. $this->drupalGet('admin/structure/types/manage/article'); $this->clickLink(t('Delete')); $this->assertResponse(200); $this->drupalPostForm(NULL, array(), t('Delete')); // Try to install search_api_db_defaults module and test if it failed // because there was no content type "article". $this->drupalPostForm('admin/modules', $edit_enable, t('Install')); $success_text = t('Content type @content_type not found. Database Search Defaults module could not be installed.', array('@content_type' => 'article')); $this->assertText($success_text); }
/** * Loads the search index belonging to the given Views base table. * * @param string $table * The Views base table ID. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * (optional) The entity manager to use. * * @return \Drupal\search_api\IndexInterface|null * The requested search index, or NULL if it could not be found and loaded. */ public static function getIndexFromTable($table, EntityManagerInterface $entity_manager = NULL) { if (substr($table, 0, 17) == 'search_api_index_') { $index_id = substr($table, 17); if ($entity_manager) { return $entity_manager->getStorage('search_api_index')->load($index_id); } return Index::load($index_id); } return NULL; }
/** * Retrieves a list of all available fulltext fields. * * @return string[] * An options list of fulltext field identifiers mapped to their prefixed * labels. */ protected function getFulltextFields() { $fields = array(); $index = Index::load(substr($this->table, 17)); $fields_info = $index->getFields(); foreach ($index->getFulltextFields() as $field_id) { $fields[$field_id] = $fields_info[$field_id]->getPrefixedLabel(); } return $fields; }
/** * Retrieves the search index used by this test. * * @return \Drupal\search_api\IndexInterface * The search index. */ protected function getIndex() { return Index::load($this->indexId); }
/** * Processes all pending index tasks inside a batch run. * * @param array $context * The current batch context. * @param \Drupal\Core\Config\ConfigImporter $config_importer * The config importer. */ public static function processIndexTasks(array &$context, ConfigImporter $config_importer) { $index_task_manager = \Drupal::getContainer()->get('search_api.index_task_manager'); if (!isset($context['sandbox']['indexes'])) { $context['sandbox']['indexes'] = array(); $indexes = \Drupal::entityTypeManager()->getStorage('search_api_index')->loadByProperties(array('status' => TRUE)); $deleted = $config_importer->getUnprocessedConfiguration('delete'); /** @var \Drupal\search_api\IndexInterface $index */ foreach ($indexes as $index_id => $index) { if (!$index_task_manager->isTrackingComplete($index) && !in_array($index->getConfigDependencyName(), $deleted)) { $context['sandbox']['indexes'][] = $index_id; } } $context['sandbox']['total'] = count($context['sandbox']['indexes']); if (!$context['sandbox']['total']) { $context['finished'] = 1; return; } } $index_id = array_shift($context['sandbox']['indexes']); $index = Index::load($index_id); $added = $index_task_manager->addItemsOnce($index); if ($added !== NULL) { array_unshift($context['sandbox']['indexes'], $index_id); } if (empty($context['sandbox']['indexes'])) { $context['finished'] = 1; } else { $finished = $context['sandbox']['total'] - count($context['sandbox']['indexes']); $context['finished'] = $finished / $context['sandbox']['total']; $args = array('%index' => $index->label(), '@num' => $finished + 1, '@total' => $context['sandbox']['total']); $context['message'] = \Drupal::translation()->translate('Tracking items for search index %index (@num of @total)', $args); } }
/** * Retrieves an options list of all available fields. * * @return string[] * An associative array mapping all indexed fields' identifiers to their * prefixed labels. * * @throws \Drupal\search_api\SearchApiException * Thrown if there couldn't be a search index retrieved for the current * view. */ protected function getFieldOptions() { if (!isset($this->field_options)) { $index_id = $this->getSearchIndexId(); /** @var \Drupal\search_api\IndexInterface $index */ $index = NULL; if (!($index_id && ($index = Index::load($index_id)))) { $table = $this->view->storage->get('base_table'); $views_data = Views::viewsData($table); $table = empty($views_data['table']['base']['title']) ? $table : $views_data['table']['base']['title']; throw new SearchApiException(SafeMarkup::format('The "Facets block" display cannot be used with a view for @base_table. Please only use this display with base tables representing Search API indexes.', array('@base_table' => $table))); } $this->field_options = array(); foreach ($index->getFields() as $key => $field) { $this->field_options[$key] = $field->getPrefixedLabel(); } } return $this->field_options; }
/** * Indexes all (unindexed) items on the specified index. * * @param string $index_id * The ID of the index on which items should be indexed. * * @return int * The number of successfully indexed items. */ protected function indexItems($index_id) { /** @var \Drupal\search_api\IndexInterface $index */ $index = Index::load($index_id); return $index->indexItems(); }
/** * Counts the number of unindexed items in the test index. * * @return int * The number of unindexed items in the test index. */ protected function countRemainingItems() { $index = Index::load($this->indexId); return $index->getTracker()->getRemainingItemsCount(); }
/** * Retrieves a list of all available fulltext fields. * * @return string[] * An options list of fulltext field identifiers mapped to their prefixed * labels. */ protected function getFulltextFields() { $fields = array(); /** @var \Drupal\search_api\IndexInterface $index */ $index = Index::load(substr($this->table, 17)); $fields_info = $index->getFields(); foreach ($index->getFulltextFields() as $field_id) { $fields[$field_id] = $fields_info[$field_id]->getPrefixedLabel(); } return $fields; }
/** * Implements the magic __wakeup() method to control object unserialization. */ public function __wakeup() { if ($this->indexId) { $this->index = Index::load($this->indexId); unset($this->indexId); } }
/** * {@inheritdoc} */ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) { try { parent::init($view, $display, $options); $this->fields = array(); if (substr($view->storage->get('base_table'), 0, 17) == 'search_api_index_') { $id = substr($view->storage->get('base_table'), 17); $this->index = Index::load($id); $this->query = $this->index->query(array('parse mode' => $this->options['parse_mode'])); } else { $this->abort(SafeMarkup::format('View %view is not based on Search API but tries to use its query plugin.', array('%view' => $view->storage->label()))); } } catch (\Exception $e) { $this->abort($e->getMessage()); } }
/** * Loads the search index belonging to the given Views base table. * * @param string $table * The Views base table ID. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * (optional) The entity type manager to use. * * @return \Drupal\search_api\IndexInterface|null * The requested search index, or NULL if it could not be found and loaded. */ public static function getIndexFromTable($table, EntityTypeManagerInterface $entity_type_manager = NULL) { // @todo Instead use Views::viewsData() – injected, too – to load the base // table definition and use the "index" (or maybe rename to // "search_api_index") field from there. if (substr($table, 0, 17) == 'search_api_index_') { $index_id = substr($table, 17); if ($entity_type_manager) { return $entity_type_manager->getStorage('search_api_index')->load($index_id); } return Index::load($index_id); } return NULL; }
/** * {@inheritdoc} */ protected function checkModuleUninstall() { // See whether clearing the server works. // Regression test for #2156151. $server = Server::load($this->serverId); $index = Index::load($this->indexId); $server->deleteAllItems($index); // Deleting items take at least 1 second for Solr to parse it so that drupal // doesn't get timeouts while waiting for Solr. Lets give it 2 seconds to // make sure we are in bounds. sleep(2); $query = $this->buildSearch(); $results = $query->execute(); $this->assertEqual($results->getResultCount(), 0, 'Clearing the server worked correctly.'); }
/** * Indexes all (unindexed) items on the specified index. * * @param string $index_id * The ID of the index on which items should be indexed. * * @return int * The number of successfully indexed items. */ protected function indexItems($index_id) { $index = Index::load($index_id); return $index->index(); }
/** * Creates or deletes an index. * * @param string $name * (optional) The name of the index. * @param string $id * (optional) The ID of the index. * @param string $server_id * (optional) The server to which the index should be attached. * @param string $datasource_id * (optional) The ID of a datasource to set for this index. * @param bool $reset * (optional) If TRUE, delete the index instead of creating it. (Only the * index's ID is required in that case.) * * @return \Drupal\search_api\IndexInterface * A search index. */ public function getTestIndex($name = 'WebTest Index', $id = 'webtest_index', $server_id = 'webtest_server', $datasource_id = 'entity:node', $reset = FALSE) { if ($reset) { /** @var \Drupal\search_api\IndexInterface $index */ $index = Index::load($id); if ($index) { $index->delete(); } } else { $index = Index::create(array('id' => $id, 'name' => $name, 'description' => $name . ' description', 'server' => $server_id, 'datasource_settings' => array($datasource_id => array('plugin_id' => $datasource_id, 'settings' => array())))); $index->save(); $this->indexId = $index->id(); } return $index; }
/** * Tests whether removing the configuration again works as it should. */ protected function checkModuleUninstall() { // See whether clearing the server works. // Regression test for #2156151. $server = Server::load($this->serverId); $index = Index::load($this->indexId); $server->deleteAllIndexItems($index); $query = $this->buildSearch(); $results = $query->execute(); $this->assertEqual($results->getResultCount(), 0, 'Clearing the server worked correctly.'); $table = 'search_api_db_' . $this->indexId; $this->assertTrue(db_table_exists($table), 'The index tables were left in place.'); // Remove first the index and then the server. $index->setServer(); $index->save(); $server = Server::load($this->serverId); $this->assertEqual($server->getBackendConfig()['field_tables'], array(), 'The index was successfully removed from the server.'); $this->assertFalse(db_table_exists($table), 'The index tables were deleted.'); $server->delete(); // Uninstall the module. \Drupal::service('module_installer')->uninstall(array('search_api_db'), FALSE); #\Drupal::moduleHandler()->uninstall(array('search_api_db'), FALSE); $this->assertFalse(\Drupal::moduleHandler()->moduleExists('search_api_db'), 'The Database Search module was successfully disabled.'); $prefix = \Drupal::database()->prefixTables('{search_api_db_}') . '%'; $this->assertEqual(\Drupal::database()->schema()->findTables($prefix), array(), 'The Database Search module was successfully uninstalled.'); }
/** * {@inheritdoc} */ public function getFulltextFields() { $fields = array(); if (!empty($this->index)) { /* @var $index \Drupal\search_api\IndexInterface */ $index = Index::load($this->index); $fields_info = $index->getFields(); foreach ($index->getFulltextFields() as $field_id) { $fields[$field_id] = $fields_info[$field_id]->getPrefixedLabel(); } } return $fields; }