updated core and modules

This commit is contained in:
Bachir Soussi Chiadmi
2017-09-09 16:27:51 +02:00
parent 027aa99b32
commit 41863f872c
7810 changed files with 318922 additions and 83631 deletions
@@ -72,14 +72,14 @@ class SearchController extends ControllerBase {
* The search form and search results build array.
*/
public function view(Request $request, SearchPageInterface $entity) {
$build = array();
$build = [];
$plugin = $entity->getPlugin();
// Build the form first, because it may redirect during the submit,
// and we don't want to build the results based on last time's request.
$build['#cache']['contexts'][] = 'url.query_args:keys';
if ($request->query->has('keys')) {
$keys = trim($request->get('keys'));
$keys = trim($request->query->get('keys'));
$plugin->setSearch($keys, $request->query->all(), $request->attributes->all());
}
@@ -89,12 +89,12 @@ class SearchController extends ControllerBase {
// Build search results, if keywords or other search parameters are in the
// GET parameters. Note that we need to try the search if 'keys' is in
// there at all, vs. being empty, due to advanced search.
$results = array();
$results = [];
if ($request->query->has('keys')) {
if ($plugin->isSearchExecutable()) {
// Log the search.
if ($this->config('search.settings')->get('logging')) {
$this->logger->notice('Searched %type for %keys.', array('%keys' => $keys, '%type' => $entity->label()));
$this->logger->notice('Searched %type for %keys.', ['%keys' => $keys, '%type' => $entity->label()]);
}
// Collect the search results.
@@ -108,22 +108,22 @@ class SearchController extends ControllerBase {
}
if (count($results)) {
$build['search_results_title'] = array(
$build['search_results_title'] = [
'#markup' => '<h2>' . $this->t('Search results') . '</h2>',
);
];
}
$build['search_results'] = array(
'#theme' => array('item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'),
$build['search_results'] = [
'#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],
'#items' => $results,
'#empty' => array(
'#empty' => [
'#markup' => '<h3>' . $this->t('Your search yielded no results.') . '</h3>',
),
],
'#list_type' => 'ol',
'#context' => array(
'#context' => [
'plugin' => $plugin->getPluginId(),
),
);
],
];
$this->renderer->addCacheableDependency($build, $entity);
if ($plugin instanceof CacheableDependencyInterface) {
@@ -138,9 +138,9 @@ class SearchController extends ControllerBase {
$build['search_results']['#cache']['tags'][] = 'search_index:' . $plugin->getType();
}
$build['pager'] = array(
$build['pager'] = [
'#type' => 'pager',
);
];
return $build;
}
@@ -157,7 +157,7 @@ class SearchController extends ControllerBase {
* The search help page.
*/
public function searchHelp(SearchPageInterface $entity) {
$build = array();
$build = [];
$build['search_help'] = $entity->getPlugin()->getHelp();
@@ -189,7 +189,7 @@ class SearchController extends ControllerBase {
* The title for the search page edit form.
*/
public function editTitle(SearchPageInterface $search_page) {
return $this->t('Edit %label search page', array('%label' => $search_page->label()));
return $this->t('Edit %label search page', ['%label' => $search_page->label()]);
}
/**
@@ -207,10 +207,10 @@ class SearchController extends ControllerBase {
$search_page->$op()->save();
if ($op == 'enable') {
drupal_set_message($this->t('The %label search page has been enabled.', array('%label' => $search_page->label())));
drupal_set_message($this->t('The %label search page has been enabled.', ['%label' => $search_page->label()]));
}
elseif ($op == 'disable') {
drupal_set_message($this->t('The %label search page has been disabled.', array('%label' => $search_page->label())));
drupal_set_message($this->t('The %label search page has been disabled.', ['%label' => $search_page->label()]));
}
$url = $search_page->urlInfo('collection');
@@ -230,7 +230,7 @@ class SearchController extends ControllerBase {
// Set the default page to this search page.
$this->searchPageRepository->setDefaultSearchPage($search_page);
drupal_set_message($this->t('The default search page is now %label. Be sure to check the ordering of your search pages.', array('%label' => $search_page->label())));
drupal_set_message($this->t('The default search page is now %label. Be sure to check the ordering of your search pages.', ['%label' => $search_page->label()]));
return $this->redirect('entity.search_page.collection');
}
@@ -73,7 +73,7 @@ class SearchPage extends ConfigEntityBase implements SearchPageInterface, Entity
*
* @var array
*/
protected $configuration = array();
protected $configuration = [];
/**
* The search plugin ID.
@@ -129,7 +129,7 @@ class SearchPage extends ConfigEntityBase implements SearchPageInterface, Entity
* {@inheritdoc}
*/
public function getPluginCollections() {
return array('configuration' => $this->getPluginCollection());
return ['configuration' => $this->getPluginCollection()];
}
/**
@@ -42,7 +42,7 @@ class SearchBlockForm extends FormBase {
* The search page repository.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\Render\RendererInterface
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
*/
public function __construct(SearchPageRepositoryInterface $search_page_repository, ConfigFactoryInterface $config_factory, RendererInterface $renderer) {
@@ -75,10 +75,18 @@ class SearchBlockForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
// Set up the form to submit using GET to the correct search page.
$entity_id = $this->searchPageRepository->getDefaultSearchPage();
// SearchPageRepository::getDefaultSearchPage() depends on search.settings.
// The dependency needs to be added before the conditional return, otherwise
// the block would get cached without the necessary cacheablity metadata in
// case there is no default search page and would not be invalidated if that
// changes.
$this->renderer->addCacheableDependency($form, $this->configFactory->get('search.settings'));
if (!$entity_id) {
$form['message'] = array(
$form['message'] = [
'#markup' => $this->t('Search is currently disabled'),
);
];
return $form;
}
@@ -86,25 +94,22 @@ class SearchBlockForm extends FormBase {
$form['#action'] = $this->url($route);
$form['#method'] = 'get';
$form['keys'] = array(
$form['keys'] = [
'#type' => 'search',
'#title' => $this->t('Search'),
'#title_display' => 'invisible',
'#size' => 15,
'#default_value' => '',
'#attributes' => array('title' => $this->t('Enter the terms you wish to search for.')),
);
'#attributes' => ['title' => $this->t('Enter the terms you wish to search for.')],
];
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Search'),
// Prevent op from showing up in the query string.
'#name' => '',
);
// SearchPageRepository::getDefaultSearchPage() depends on search.settings.
$this->renderer->addCacheableDependency($form, $this->configFactory->get('search.settings'));
];
return $form;
}
@@ -24,7 +24,7 @@ class SearchPageAddForm extends SearchPageFormBase {
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions = parent::actions($form, $form_state);
$actions['submit']['#value'] = $this->t('Add search page');
$actions['submit']['#value'] = $this->t('Save');
return $actions;
}
@@ -39,7 +39,7 @@ class SearchPageAddForm extends SearchPageFormBase {
parent::save($form, $form_state);
drupal_set_message($this->t('The %label search page has been added.', array('%label' => $this->entity->label())));
drupal_set_message($this->t('The %label search page has been added.', ['%label' => $this->entity->label()]));
}
}
@@ -24,7 +24,7 @@ class SearchPageEditForm extends SearchPageFormBase {
public function save(array $form, FormStateInterface $form_state) {
parent::save($form, $form_state);
drupal_set_message($this->t('The %label search page has been updated.', array('%label' => $this->entity->label())));
drupal_set_message($this->t('The %label search page has been updated.', ['%label' => $this->entity->label()]));
}
}
+17 -17
View File
@@ -38,37 +38,37 @@ class SearchPageForm extends EntityForm {
$plugin = $this->entity->getPlugin();
$form_state->set('search_page_id', $this->entity->id());
$form['basic'] = array(
$form['basic'] = [
'#type' => 'container',
'#attributes' => array(
'class' => array('container-inline'),
),
);
$form['basic']['keys'] = array(
'#attributes' => [
'class' => ['container-inline'],
],
];
$form['basic']['keys'] = [
'#type' => 'search',
'#title' => $this->t('Enter your keywords'),
'#default_value' => $plugin->getKeywords(),
'#size' => 30,
'#maxlength' => 255,
);
];
// processed_keys is used to coordinate keyword passing between other forms
// that hook into the basic search form.
$form['basic']['processed_keys'] = array(
$form['basic']['processed_keys'] = [
'#type' => 'value',
'#value' => '',
);
$form['basic']['submit'] = array(
];
$form['basic']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Search'),
);
];
$form['help_link'] = array(
$form['help_link'] = [
'#type' => 'link',
'#url' => new Url('search.help_' . $this->entity->id()),
'#title' => $this->t('Search help'),
'#options' => array('attributes' => array('class' => 'search-help-link')),
);
'#options' => ['attributes' => ['class' => 'search-help-link']],
];
// Allow the plugin to add to or alter the search form.
$plugin->searchFormAlter($form, $form_state);
@@ -81,7 +81,7 @@ class SearchPageForm extends EntityForm {
*/
protected function actions(array $form, FormStateInterface $form_state) {
// The submit button is added in the form directly.
return array();
return [];
}
/**
@@ -97,8 +97,8 @@ class SearchPageForm extends EntityForm {
$route = 'search.view_' . $form_state->get('search_page_id');
$form_state->setRedirect(
$route,
array(),
array('query' => $query)
[],
['query' => $query]
);
}
@@ -3,7 +3,6 @@
namespace Drupal\search\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\search\SearchPageRepositoryInterface;
@@ -28,13 +27,6 @@ abstract class SearchPageFormBase extends EntityForm {
*/
protected $plugin;
/**
* The entity query factory.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $entityQuery;
/**
* The search page repository.
*
@@ -45,13 +37,10 @@ abstract class SearchPageFormBase extends EntityForm {
/**
* Constructs a new search form.
*
* @param \Drupal\Core\Entity\Query\QueryFactory $entity_query
* The entity query.
* @param \Drupal\search\SearchPageRepositoryInterface $search_page_repository
* The search page repository.
*/
public function __construct(QueryFactory $entity_query, SearchPageRepositoryInterface $search_page_repository) {
$this->entityQuery = $entity_query;
public function __construct(SearchPageRepositoryInterface $search_page_repository) {
$this->searchPageRepository = $search_page_repository;
}
@@ -60,7 +49,6 @@ abstract class SearchPageFormBase extends EntityForm {
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.query'),
$container->get('search.search_page_repository')
);
}
@@ -84,35 +72,35 @@ abstract class SearchPageFormBase extends EntityForm {
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form['label'] = array(
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#description' => $this->t('The label for this search page.'),
'#default_value' => $this->entity->label(),
'#maxlength' => '255',
);
];
$form['id'] = array(
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $this->entity->id(),
'#disabled' => !$this->entity->isNew(),
'#maxlength' => 64,
'#machine_name' => array(
'exists' => array($this, 'exists'),
),
);
$form['path'] = array(
'#machine_name' => [
'exists' => [$this, 'exists'],
],
];
$form['path'] = [
'#type' => 'textfield',
'#title' => $this->t('Path'),
'#field_prefix' => 'search/',
'#default_value' => $this->entity->getPath(),
'#maxlength' => '255',
'#required' => TRUE,
);
$form['plugin'] = array(
];
$form['plugin'] = [
'#type' => 'value',
'#value' => $this->entity->get('plugin'),
);
];
if ($this->plugin instanceof PluginFormInterface) {
$form += $this->plugin->buildConfigurationForm($form, $form_state);
@@ -131,7 +119,7 @@ abstract class SearchPageFormBase extends EntityForm {
* TRUE if the search configuration exists, FALSE otherwise.
*/
public function exists($id) {
$entity = $this->entityQuery->get('search_page')
$entity = $this->entityTypeManager->getStorage('search_page')->getQuery()
->condition('id', $id)
->execute();
return (bool) $entity;
@@ -144,7 +132,7 @@ abstract class SearchPageFormBase extends EntityForm {
parent::validateForm($form, $form_state);
// Ensure each path is unique.
$path = $this->entityQuery->get('search_page')
$path = $this->entityTypeManager->getStorage('search_page')->getQuery()
->condition('path', $form_state->getValue('path'))
->condition('id', $form_state->getValue('id'), '<>')
->execute();
@@ -30,7 +30,7 @@ abstract class ConfigurableSearchPluginBase extends SearchPluginBase implements
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array();
return [];
}
/**
@@ -57,7 +57,7 @@ abstract class ConfigurableSearchPluginBase extends SearchPluginBase implements
* {@inheritdoc}
*/
public function calculateDependencies() {
return array();
return [];
}
/**
@@ -42,17 +42,17 @@ class SearchLocalTask extends DeriverBase implements ContainerDeriverInterface {
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$this->derivatives = array();
$this->derivatives = [];
if ($default = $this->searchPageRepository->getDefaultSearchPage()) {
$active_search_pages = $this->searchPageRepository->getActiveSearchPages();
foreach ($this->searchPageRepository->sortSearchPages($active_search_pages) as $entity_id => $entity) {
$this->derivatives[$entity_id] = array(
$this->derivatives[$entity_id] = [
'title' => $entity->label(),
'route_name' => 'search.view_' . $entity_id,
'base_route' => 'search.plugins:' . $default,
'weight' => $entity->getWeight(),
);
];
}
}
return $this->derivatives;
@@ -97,13 +97,13 @@ abstract class SearchPluginBase extends PluginBase implements ContainerFactoryPl
public function buildResults() {
$results = $this->execute();
$built = array();
$built = [];
foreach ($results as $result) {
$built[] = array(
$built[] = [
'#theme' => 'search_result',
'#result' => $result,
'#plugin_id' => $this->getPluginId(),
);
];
}
return $built;
@@ -123,7 +123,7 @@ abstract class SearchPluginBase extends PluginBase implements ContainerFactoryPl
// If the user entered a search string, truncate it and append it to the
// title.
if (!empty($this->keywords)) {
return $this->t('Search for @keywords', array('@keywords' => Unicode::truncate($this->keywords, 60, TRUE, TRUE)));
return $this->t('Search for @keywords', ['@keywords' => Unicode::truncate($this->keywords, 60, TRUE, TRUE)]);
}
// Use the default 'Search' title.
return $this->t('Search');
@@ -135,7 +135,7 @@ abstract class SearchPluginBase extends PluginBase implements ContainerFactoryPl
public function buildSearchUrlQuery(FormStateInterface $form_state) {
// Grab the keywords entered in the form and put them as 'keys' in the GET.
$keys = trim($form_state->getValue('keys'));
$query = array('keys' => $keys);
$query = ['keys' => $keys];
return $query;
}
@@ -146,16 +146,16 @@ abstract class SearchPluginBase extends PluginBase implements ContainerFactoryPl
public function getHelp() {
// This default search help is appropriate for plugins like NodeSearch
// that use the SearchQuery class.
$help = array('list' => array(
$help = ['list' => [
'#theme' => 'item_list',
'#items' => array(
'#items' => [
$this->t('Search looks for exact, case-insensitive keywords; keywords shorter than a minimum length are ignored.'),
$this->t('Use upper-case OR to get more results. Example: cat OR dog (content contains either "cat" or "dog").'),
$this->t('You can use upper-case AND to require all words, but this is the same as the default behavior. Example: cat AND dog (same as cat dog, content must contain both "cat" and "dog").'),
$this->t('Use quotes to search for a phrase. Example: "the cat eats mice".'),
$this->t('You can precede keywords by - to exclude them; you must still have at least one "positive" keyword. Example: cat -dog (content must contain cat and cannot contain dog).'),
),
));
],
]];
return $help;
}
@@ -21,7 +21,7 @@ class SearchConfigurationRankings extends ProcessPluginBase {
* Generate the configuration rankings.
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$return = array();
$return = [];
foreach ($row->getSource() as $name => $rank) {
if (substr($name, 0, 10) == 'node_rank_' && is_numeric($rank)) {
$return[substr($name, 10)] = $rank;
@@ -21,7 +21,7 @@ class SearchConfigurationRankings extends ProcessPluginBase {
* Generate the configuration rankings.
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
$return = array();
$return = [];
foreach ($row->getSource() as $name => $rank) {
if (substr($name, 0, 10) == 'node_rank_' && $rank) {
$return[substr($name, 10)] = $rank;
@@ -47,7 +47,7 @@ class Search extends ArgumentPluginBase {
*/
protected function queryParseSearchExpression($input) {
if (!isset($this->searchQuery)) {
$this->searchQuery = db_select('search_index', 'i', array('target' => 'replica'))->extend('Drupal\search\ViewsSearchQuery');
$this->searchQuery = db_select('search_index', 'i', ['target' => 'replica'])->extend('Drupal\search\ViewsSearchQuery');
$this->searchQuery->searchExpression($input, $this->searchType);
$this->searchQuery->publicParseSearchExpression();
}
@@ -79,17 +79,17 @@ class Search extends ArgumentPluginBase {
$search_condition = db_and();
// Create a new join to relate the 'search_total' table to our current 'search_index' table.
$definition = array(
$definition = [
'table' => 'search_total',
'field' => 'word',
'left_table' => $search_index,
'left_field' => 'word',
);
];
$join = Views::pluginManager('join')->createInstance('standard', $definition);
$search_total = $this->query->addRelationship('search_total', $join, $search_index);
// Add the search score field to the query.
$this->search_score = $this->query->addField('', "$search_index.score * $search_total.count", 'score', array('function' => 'sum'));
$this->search_score = $this->query->addField('', "$search_index.score * $search_total.count", 'score', ['function' => 'sum']);
// Add the conditions set up by the search query to the views query.
$search_condition->condition("$search_index.type", $this->searchType);
@@ -120,7 +120,7 @@ class Search extends ArgumentPluginBase {
$this->query->addGroupBy("$search_index.sid");
$matches = $this->searchQuery->matches();
$placeholder = $this->placeholder();
$this->query->addHavingExpression(0, "COUNT(*) >= $placeholder", array($placeholder => $matches));
$this->query->addHavingExpression(0, "COUNT(*) >= $placeholder", [$placeholder => $matches]);
}
// Set to NULL to prevent PDO exception when views object is cached
@@ -67,28 +67,28 @@ class Search extends FilterPluginBase {
* {@inheritdoc}
*/
protected function operatorForm(&$form, FormStateInterface $form_state) {
$form['operator'] = array(
$form['operator'] = [
'#type' => 'radios',
'#title' => $this->t('On empty input'),
'#default_value' => $this->operator,
'#options' => array(
'#options' => [
'optional' => $this->t('Show All'),
'required' => $this->t('Show None'),
),
);
],
];
}
/**
* {@inheritdoc}
*/
protected function valueForm(&$form, FormStateInterface $form_state) {
$form['value'] = array(
$form['value'] = [
'#type' => 'textfield',
'#size' => 15,
'#default_value' => $this->value,
'#attributes' => array('title' => $this->t('Search keywords')),
'#attributes' => ['title' => $this->t('Search keywords')],
'#title' => !$form_state->get('exposed') ? $this->t('Keywords') : '',
);
];
}
/**
@@ -117,7 +117,7 @@ class Search extends FilterPluginBase {
protected function queryParseSearchExpression($input) {
if (!isset($this->searchQuery)) {
$this->parsed = TRUE;
$this->searchQuery = db_select('search_index', 'i', array('target' => 'replica'))->extend('Drupal\search\ViewsSearchQuery');
$this->searchQuery = db_select('search_index', 'i', ['target' => 'replica'])->extend('Drupal\search\ViewsSearchQuery');
$this->searchQuery->searchExpression($input, $this->searchType);
$this->searchQuery->publicParseSearchExpression();
}
@@ -154,17 +154,17 @@ class Search extends FilterPluginBase {
// Create a new join to relate the 'search_total' table to our current
// 'search_index' table.
$definition = array(
$definition = [
'table' => 'search_total',
'field' => 'word',
'left_table' => $search_index,
'left_field' => 'word',
);
];
$join = Views::pluginManager('join')->createInstance('standard', $definition);
$search_total = $this->query->addRelationship('search_total', $join, $search_index);
// Add the search score field to the query.
$this->search_score = $this->query->addField('', "$search_index.score * $search_total.count", 'score', array('function' => 'sum'));
$this->search_score = $this->query->addField('', "$search_index.score * $search_total.count", 'score', ['function' => 'sum']);
// Add the conditions set up by the search query to the views query.
$search_condition->condition("$search_index.type", $this->searchType);
@@ -196,7 +196,7 @@ class Search extends FilterPluginBase {
$this->query->addGroupBy("$search_index.sid");
$matches = $this->searchQuery->matches();
$placeholder = $this->placeholder();
$this->query->addHavingExpression($this->options['group'], "COUNT(*) >= $placeholder", array($placeholder => $matches));
$this->query->addHavingExpression($this->options['group'], "COUNT(*) >= $placeholder", [$placeholder => $matches]);
}
// Set to NULL to prevent PDO exception when views object is cached.
$this->searchQuery = NULL;
@@ -22,7 +22,7 @@ class SearchRow extends RowPluginBase {
protected function defineOptions() {
$options = parent::defineOptions();
$options['score'] = array('default' => TRUE);
$options['score'] = ['default' => TRUE];
return $options;
}
@@ -31,23 +31,23 @@ class SearchRow extends RowPluginBase {
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['score'] = array(
$form['score'] = [
'#type' => 'checkbox',
'#title' => $this->t('Display score'),
'#default_value' => $this->options['score'],
);
];
}
/**
* {@inheritdoc}
*/
public function render($row) {
return array(
return [
'#theme' => $this->themeFunctions(),
'#view' => $this->view,
'#options' => $this->options,
'#row' => $row,
);
];
}
}
@@ -21,7 +21,7 @@ class Score extends SortPluginBase {
// Our filter stores it as $handler->search_score -- and we also
// need to check its relationship to make sure that we're using the same
// one or obviously this won't work.
foreach (array('filter', 'argument') as $type) {
foreach (['filter', 'argument'] as $type) {
foreach ($this->view->{$type} as $handler) {
if (isset($handler->search_score) && $handler->relationship == $this->relationship) {
$this->query->addOrderBy(NULL, NULL, $this->options['order'], $handler->search_score);
@@ -45,70 +45,70 @@ class SearchPageRoutes implements ContainerInjectionInterface {
* An array of route objects.
*/
public function routes() {
$routes = array();
$routes = [];
// @todo Decide if /search should continue to redirect to /search/$default,
// or just perform the appropriate search.
if ($default_page = $this->searchPageRepository->getDefaultSearchPage()) {
$routes['search.view'] = new Route(
'/search',
array(
[
'_controller' => 'Drupal\search\Controller\SearchController::redirectSearchPage',
'_title' => 'Search',
'entity' => $default_page,
),
array(
],
[
'_entity_access' => 'entity.view',
'_permission' => 'search content',
),
array(
'parameters' => array(
'entity' => array(
],
[
'parameters' => [
'entity' => [
'type' => 'entity:search_page',
),
),
)
],
],
]
);
}
$active_pages = $this->searchPageRepository->getActiveSearchPages();
foreach ($active_pages as $entity_id => $entity) {
$routes["search.view_$entity_id"] = new Route(
'/search/' . $entity->getPath(),
array(
[
'_controller' => 'Drupal\search\Controller\SearchController::view',
'_title' => 'Search',
'entity' => $entity_id,
),
array(
],
[
'_entity_access' => 'entity.view',
'_permission' => 'search content',
),
array(
'parameters' => array(
'entity' => array(
],
[
'parameters' => [
'entity' => [
'type' => 'entity:search_page',
),
),
)
],
],
]
);
$routes["search.help_$entity_id"] = new Route(
'/search/' . $entity->getPath() . '/help',
array(
[
'_controller' => 'Drupal\search\Controller\SearchController::searchHelp',
'_title' => 'Search help',
'entity' => $entity_id,
),
array(
],
[
'_entity_access' => 'entity.view',
'_permission' => 'search content',
),
array(
'parameters' => array(
'entity' => array(
],
[
'parameters' => [
'entity' => [
'type' => 'entity:search_page',
),
),
)
],
],
]
);
}
return $routes;
@@ -20,7 +20,7 @@ class SearchPageAccessControlHandler extends EntityAccessControlHandler {
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var $entity \Drupal\search\SearchPageInterface */
if (in_array($operation, array('delete', 'disable'))) {
if (in_array($operation, ['delete', 'disable'])) {
if ($entity->isDefaultSearch()) {
return AccessResult::forbidden()->addCacheableDependency($entity);
}
@@ -26,7 +26,7 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
*
* @var \Drupal\search\SearchPageInterface[]
*/
protected $entities = array();
protected $entities = [];
/**
* Stores the configuration factory.
@@ -90,24 +90,24 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = array(
$header['label'] = [
'data' => $this->t('Label'),
);
$header['url'] = array(
];
$header['url'] = [
'data' => $this->t('URL'),
'class' => array(RESPONSIVE_PRIORITY_LOW),
);
$header['plugin'] = array(
'class' => [RESPONSIVE_PRIORITY_LOW],
];
$header['plugin'] = [
'data' => $this->t('Type'),
'class' => array(RESPONSIVE_PRIORITY_LOW),
);
$header['status'] = array(
'class' => [RESPONSIVE_PRIORITY_LOW],
];
$header['status'] = [
'data' => $this->t('Status'),
);
$header['progress'] = array(
];
$header['progress'] = [
'data' => $this->t('Indexing progress'),
'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
);
'class' => [RESPONSIVE_PRIORITY_MEDIUM],
];
return $header + parent::buildHeader();
}
@@ -120,11 +120,11 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
$row['url']['#markup'] = 'search/' . $entity->getPath();
// If the search page is active, link to it.
if ($entity->status()) {
$row['url'] = array(
$row['url'] = [
'#type' => 'link',
'#title' => $row['url'],
'#url' => Url::fromRoute('search.view_' . $entity->id()),
);
];
}
$definition = $entity->getPlugin()->getPluginDefinition();
@@ -143,10 +143,10 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
if ($entity->isIndexable()) {
$status = $entity->getPlugin()->indexStatus();
$row['progress']['#markup'] = $this->t('%num_indexed of %num_total indexed', array(
$row['progress']['#markup'] = $this->t('%num_indexed of %num_total indexed', [
'%num_indexed' => $status['total'] - $status['remaining'],
'%num_total' => $status['total']
));
]);
}
else {
$row['progress']['#markup'] = $this->t('Does not use index');
@@ -178,102 +178,102 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
// will show as 99%, to indicate "almost done".
$percentage = $total > 0 ? floor(100 * $done / $total) : 100;
$percentage .= '%';
$status = '<p><strong>' . $this->t('%percentage of the site has been indexed.', array('%percentage' => $percentage)) . ' ' . $count . '</strong></p>';
$form['status'] = array(
$status = '<p><strong>' . $this->t('%percentage of the site has been indexed.', ['%percentage' => $percentage]) . ' ' . $count . '</strong></p>';
$form['status'] = [
'#type' => 'details',
'#title' => $this->t('Indexing progress'),
'#open' => TRUE,
'#description' => $this->t('Only items in the index will appear in search results. To build and maintain the index, a correctly configured <a href=":cron">cron maintenance task</a> is required.', array(':cron' => \Drupal::url('system.cron_settings'))),
);
$form['status']['status'] = array('#markup' => $status);
$form['status']['wipe'] = array(
'#description' => $this->t('Only items in the index will appear in search results. To build and maintain the index, a correctly configured <a href=":cron">cron maintenance task</a> is required.', [':cron' => \Drupal::url('system.cron_settings')]),
];
$form['status']['status'] = ['#markup' => $status];
$form['status']['wipe'] = [
'#type' => 'submit',
'#value' => $this->t('Re-index site'),
'#submit' => array('::searchAdminReindexSubmit'),
);
'#submit' => ['::searchAdminReindexSubmit'],
];
$items = array(10, 20, 50, 100, 200, 500);
$items = [10, 20, 50, 100, 200, 500];
$items = array_combine($items, $items);
// Indexing throttle:
$form['indexing_throttle'] = array(
$form['indexing_throttle'] = [
'#type' => 'details',
'#title' => $this->t('Indexing throttle'),
'#open' => TRUE,
);
$form['indexing_throttle']['cron_limit'] = array(
];
$form['indexing_throttle']['cron_limit'] = [
'#type' => 'select',
'#title' => $this->t('Number of items to index per cron run'),
'#default_value' => $search_settings->get('index.cron_limit'),
'#options' => $items,
'#description' => $this->t('The maximum number of items indexed in each run of the <a href=":cron">cron maintenance task</a>. If necessary, reduce the number of items to prevent timeouts and memory errors while indexing. Some search page types may have their own setting for this.', array(':cron' => \Drupal::url('system.cron_settings'))),
);
'#description' => $this->t('The maximum number of items indexed in each run of the <a href=":cron">cron maintenance task</a>. If necessary, reduce the number of items to prevent timeouts and memory errors while indexing. Some search page types may have their own setting for this.', [':cron' => \Drupal::url('system.cron_settings')]),
];
// Indexing settings:
$form['indexing_settings'] = array(
$form['indexing_settings'] = [
'#type' => 'details',
'#title' => $this->t('Default indexing settings'),
'#open' => TRUE,
);
$form['indexing_settings']['info'] = array(
];
$form['indexing_settings']['info'] = [
'#markup' => $this->t("<p>Search pages that use an index may use the default index provided by the Search module, or they may use a different indexing mechanism. These settings are for the default index. <em>Changing these settings will cause the default search index to be rebuilt to reflect the new settings. Searching will continue to work, based on the existing index, but new content won't be indexed until all existing content has been re-indexed.</em></p><p><em>The default settings should be appropriate for the majority of sites.</em></p>")
);
$form['indexing_settings']['minimum_word_size'] = array(
];
$form['indexing_settings']['minimum_word_size'] = [
'#type' => 'number',
'#title' => $this->t('Minimum word length to index'),
'#default_value' => $search_settings->get('index.minimum_word_size'),
'#min' => 1,
'#max' => 1000,
'#description' => $this->t('The minimum character length for a word to be added to the index. Searches must include a keyword of at least this length.'),
);
$form['indexing_settings']['overlap_cjk'] = array(
];
$form['indexing_settings']['overlap_cjk'] = [
'#type' => 'checkbox',
'#title' => $this->t('Simple CJK handling'),
'#default_value' => $search_settings->get('index.overlap_cjk'),
'#description' => $this->t('Whether to apply a simple Chinese/Japanese/Korean tokenizer based on overlapping sequences. Turn this off if you want to use an external preprocessor for this instead. Does not affect other languages.')
);
];
// Indexing settings:
$form['logging'] = array(
$form['logging'] = [
'#type' => 'details',
'#title' => $this->t('Logging'),
'#open' => TRUE,
);
];
$form['logging']['logging'] = array(
$form['logging']['logging'] = [
'#type' => 'checkbox',
'#title' => $this->t('Log searches'),
'#default_value' => $search_settings->get('logging'),
'#description' => $this->t('If checked, all searches will be logged. Uncheck to skip logging. Logging may affect performance.'),
);
];
$form['search_pages'] = array(
$form['search_pages'] = [
'#type' => 'details',
'#title' => $this->t('Search pages'),
'#open' => TRUE,
);
$form['search_pages']['add_page'] = array(
];
$form['search_pages']['add_page'] = [
'#type' => 'container',
'#attributes' => array(
'class' => array('container-inline'),
),
);
'#attributes' => [
'class' => ['container-inline'],
],
];
// In order to prevent validation errors for the parent form, this cannot be
// required, see self::validateAddSearchPage().
$form['search_pages']['add_page']['search_type'] = array(
$form['search_pages']['add_page']['search_type'] = [
'#type' => 'select',
'#title' => $this->t('Search page type'),
'#empty_option' => $this->t('- Choose page type -'),
'#options' => array_map(function ($definition) {
return $definition['title'];
}, $this->searchManager->getDefinitions()),
);
$form['search_pages']['add_page']['add_search_submit'] = array(
];
$form['search_pages']['add_page']['add_search_submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add new page'),
'#validate' => array('::validateAddSearchPage'),
'#submit' => array('::submitAddSearchPage'),
'#limit_validation_errors' => array(array('search_type')),
);
'#value' => $this->t('Add search page'),
'#validate' => ['::validateAddSearchPage'],
'#submit' => ['::submitAddSearchPage'],
'#limit_validation_errors' => [['search_type']],
];
// Move the listing into the search_pages element.
$form['search_pages'][$this->entitiesKey] = $form[$this->entitiesKey];
@@ -281,11 +281,11 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
unset($form[$this->entitiesKey]);
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save configuration'),
'#button_type' => 'primary',
);
];
return $form;
}
@@ -302,13 +302,13 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
unset($operations['disable'], $operations['delete']);
}
else {
$operations['default'] = array(
$operations['default'] = [
'title' => $this->t('Set as default'),
'url' => Url::fromRoute('entity.search_page.set_default', [
'search_page' => $entity->id(),
]),
'weight' => 50,
);
];
}
return $operations;
@@ -369,7 +369,7 @@ class SearchPageListBuilder extends DraggableListBuilder implements FormInterfac
public function submitAddSearchPage(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect(
'search.add_type',
array('search_plugin_id' => $form_state->getValue('search_type'))
['search_plugin_id' => $form_state->getValue('search_type')]
);
}
@@ -105,7 +105,7 @@ class SearchPageRepository implements SearchPageRepositoryInterface {
*/
public function sortSearchPages($search_pages) {
$entity_type = $this->storage->getEntityType();
uasort($search_pages, array($entity_type->getClass(), 'sort'));
uasort($search_pages, [$entity_type->getClass(), 'sort']);
return $search_pages;
}
+14 -14
View File
@@ -96,7 +96,7 @@ class SearchQuery extends SelectExtender {
*
* @var array
*/
protected $keys = array('positive' => array(), 'negative' => array());
protected $keys = ['positive' => [], 'negative' => []];
/**
* Indicates whether the query conditions are simple or complex (LIKE).
@@ -129,7 +129,7 @@ class SearchQuery extends SelectExtender {
*
* @var array
*/
protected $words = array();
protected $words = [];
/**
* Multiplier to normalize the keyword score.
@@ -164,14 +164,14 @@ class SearchQuery extends SelectExtender {
*
* @see SearchQuery::addScore()
*/
protected $scores = array();
protected $scores = [];
/**
* Arguments for the score expressions.
*
* @var array
*/
protected $scoresArguments = array();
protected $scoresArguments = [];
/**
* The number of 'i.relevance' occurrences in score expressions.
@@ -185,7 +185,7 @@ class SearchQuery extends SelectExtender {
*
* @var array
*/
protected $multiply = array();
protected $multiply = [];
/**
* Sets the search query expression.
@@ -258,7 +258,7 @@ class SearchQuery extends SelectExtender {
$words = search_simplify($match[2]);
// Re-explode in case simplification added more words, except when
// matching a phrase.
$words = $phrase ? array($words) : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
$words = $phrase ? [$words] : preg_split('/ /', $words, -1, PREG_SPLIT_NO_EMPTY);
// Negative matches.
if ($match[1] == '-') {
$this->keys['negative'] = array_merge($this->keys['negative'], $words);
@@ -269,7 +269,7 @@ class SearchQuery extends SelectExtender {
$last = array_pop($this->keys['positive']);
// Starting a new OR?
if (!is_array($last)) {
$last = array($last);
$last = [$last];
}
$this->keys['positive'][] = $last;
$in_or = TRUE;
@@ -373,7 +373,7 @@ class SearchQuery extends SelectExtender {
}
// Return matching snippet and number of added words.
return array($num_new_scores, $num_valid_words);
return [$num_new_scores, $num_valid_words];
}
/**
@@ -419,7 +419,7 @@ class SearchQuery extends SelectExtender {
// simple queries, this condition could lead to incorrectly deciding not
// to continue with the full query.
if ($this->simple) {
$this->having('COUNT(*) >= :matches', array(':matches' => $this->matches));
$this->having('COUNT(*) >= :matches', [':matches' => $this->matches]);
}
// Clone the query object to calculate normalization.
@@ -498,7 +498,7 @@ class SearchQuery extends SelectExtender {
*
* @return $this
*/
public function addScore($score, $arguments = array(), $multiply = FALSE) {
public function addScore($score, $arguments = [], $multiply = FALSE) {
if ($multiply) {
$i = count($this->multiply);
// Modify the score expression so it is multiplied by the multiplier,
@@ -589,7 +589,7 @@ class SearchQuery extends SelectExtender {
// Add query metadata.
$this
->addMetaData('normalize', $this->normalize)
->fields('i', array('type', 'sid'));
->fields('i', ['type', 'sid']);
return $this->query->execute();
}
@@ -617,12 +617,12 @@ class SearchQuery extends SelectExtender {
// Remove existing fields and expressions, they are not needed for a count
// query.
$fields =& $inner->getFields();
$fields = array();
$fields = [];
$expressions =& $inner->getExpressions();
$expressions = array();
$expressions = [];
// Add sid as the only field and count them as a subquery.
$count = db_select($inner->fields('i', array('sid')), NULL, array('target' => 'replica'));
$count = db_select($inner->fields('i', ['sid']), NULL, ['target' => 'replica']);
// Add the COUNT() expression.
$count->addExpression('COUNT(*)');
@@ -19,7 +19,7 @@ class SearchAdvancedSearchFormTest extends SearchTestBase {
protected function setUp() {
parent::setUp();
// Create and log in user.
$test_user = $this->drupalCreateUser(array('access content', 'search content', 'use advanced search', 'administer nodes'));
$test_user = $this->drupalCreateUser(['access content', 'search content', 'use advanced search', 'administer nodes']);
$this->drupalLogin($test_user);
// Create initial node.
@@ -37,44 +37,44 @@ class SearchAdvancedSearchFormTest extends SearchTestBase {
/**
* Tests advanced search by node type.
*/
function testNodeType() {
public function testNodeType() {
// Verify some properties of the node that was created.
$this->assertTrue($this->node->getType() == 'page', 'Node type is Basic page.');
$dummy_title = 'Lorem ipsum';
$this->assertNotEqual($dummy_title, $this->node->label(), "Dummy title doesn't equal node title.");
// Search for the dummy title with a GET query.
$this->drupalGet('search/node', array('query' => array('keys' => $dummy_title)));
$this->drupalGet('search/node', ['query' => ['keys' => $dummy_title]]);
$this->assertNoText($this->node->label(), 'Basic page node is not found with dummy title.');
// Search for the title of the node with a GET query.
$this->drupalGet('search/node', array('query' => array('keys' => $this->node->label())));
$this->drupalGet('search/node', ['query' => ['keys' => $this->node->label()]]);
$this->assertText($this->node->label(), 'Basic page node is found with GET query.');
// Search for the title of the node with a POST query.
$edit = array('or' => $this->node->label());
$edit = ['or' => $this->node->label()];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
$this->assertText($this->node->label(), 'Basic page node is found with POST query.');
// Search by node type.
$this->drupalPostForm('search/node', array_merge($edit, array('type[page]' => 'page')), t('Advanced search'));
$this->drupalPostForm('search/node', array_merge($edit, ['type[page]' => 'page']), t('Advanced search'));
$this->assertText($this->node->label(), 'Basic page node is found with POST query and type:page.');
$this->drupalPostForm('search/node', array_merge($edit, array('type[article]' => 'article')), t('Advanced search'));
$this->drupalPostForm('search/node', array_merge($edit, ['type[article]' => 'article']), t('Advanced search'));
$this->assertText('search yielded no results', 'Article node is not found with POST query and type:article.');
}
/**
* Tests that after submitting the advanced search form, the form is refilled.
*/
function testFormRefill() {
$edit = array(
public function testFormRefill() {
$edit = [
'keys' => 'cat',
'or' => 'dog gerbil',
'phrase' => 'pets are nice',
'negative' => 'fish snake',
'type[page]' => 'page',
);
];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
// Test that the encoded query appears in the page title. Only test the
@@ -85,11 +85,11 @@ class SearchAdvancedSearchFormTest extends SearchTestBase {
// Verify that all of the form fields are filled out.
foreach ($edit as $key => $value) {
if ($key != 'type[page]') {
$elements = $this->xpath('//input[@name=:name]', array(':name' => $key));
$elements = $this->xpath('//input[@name=:name]', [':name' => $key]);
$this->assertTrue(isset($elements[0]) && $elements[0]['value'] == $value, "Field $key is set to $value");
}
else {
$elements = $this->xpath('//input[@name=:name]', array(':name' => $key));
$elements = $this->xpath('//input[@name=:name]', [':name' => $key]);
$this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), "Field $key is checked");
}
}
@@ -97,12 +97,12 @@ class SearchAdvancedSearchFormTest extends SearchTestBase {
// Now test by submitting the or/not part of the query in the main
// search box, and verify that the advanced form is not filled out.
// (It shouldn't be filled out unless you submit values in those fields.)
$edit2 = array('keys' => 'cat dog OR gerbil -fish -snake');
$edit2 = ['keys' => 'cat dog OR gerbil -fish -snake'];
$this->drupalPostForm('search/node', $edit2, t('Advanced search'));
$this->assertText('Search for cat dog OR gerbil -fish -snake');
foreach ($edit as $key => $value) {
if ($key != 'type[page]') {
$elements = $this->xpath('//input[@name=:name]', array(':name' => $key));
$elements = $this->xpath('//input[@name=:name]', [':name' => $key]);
$this->assertFalse(isset($elements[0]) && $elements[0]['value'] == $value, "Field $key is not set to $value");
}
}
@@ -14,13 +14,13 @@ class SearchBlockTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('block');
public static $modules = ['block'];
protected function setUp() {
parent::setUp();
// Create and log in user.
$admin_user = $this->drupalCreateUser(array('administer blocks', 'search content'));
$admin_user = $this->drupalCreateUser(['administer blocks', 'search content']);
$this->drupalLogin($admin_user);
}
@@ -46,7 +46,7 @@ class SearchBlockTest extends SearchTestBase {
$this->assertTrue(empty($elements), 'The search input field does not have empty name attribute.');
// Test a normal search via the block form, from the front page.
$terms = array('keys' => 'test');
$terms = ['keys' => 'test'];
$this->submitGetForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
@@ -72,12 +72,12 @@ class SearchBlockTest extends SearchTestBase {
$entity_id = $search_page_repository->getDefaultSearchPage();
$this->assertEqual(
$this->getUrl(),
\Drupal::url('search.view_' . $entity_id, array(), array('query' => array('keys' => $terms['keys']), 'absolute' => TRUE)),
\Drupal::url('search.view_' . $entity_id, [], ['query' => ['keys' => $terms['keys']], 'absolute' => TRUE]),
'Submitted to correct URL.'
);
// Test an empty search via the block form, from the front page.
$terms = array('keys' => '');
$terms = ['keys' => ''];
$this->submitGetForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Please enter some keywords');
@@ -86,22 +86,22 @@ class SearchBlockTest extends SearchTestBase {
// submitted empty.
$this->assertEqual(
$this->getUrl(),
\Drupal::url('search.view_' . $entity_id, array(), array('query' => array('keys' => ''), 'absolute' => TRUE)),
\Drupal::url('search.view_' . $entity_id, [], ['query' => ['keys' => ''], 'absolute' => TRUE]),
'Redirected to correct URL.'
);
// Test that after entering a too-short keyword in the form, you can then
// search again with a longer keyword. First test using the block form.
$this->submitGetForm('node', array('keys' => $this->randomMachineName(1)), t('Search'));
$this->submitGetForm('node', ['keys' => $this->randomMachineName(1)], t('Search'));
$this->assertText('You must include at least one keyword to match in the content', 'Keyword message is displayed when searching for short word');
$this->assertNoText(t('Please enter some keywords'), 'With short word entered, no keywords message is not displayed');
$this->submitGetForm(NULL, array('keys' => $this->randomMachineName()), t('Search'), 'search-block-form');
$this->submitGetForm(NULL, ['keys' => $this->randomMachineName()], t('Search'), 'search-block-form');
$this->assertNoText('You must include at least one keyword to match in the content', 'Keyword message is not displayed when searching for long word after short word search');
// Same test again, using the search page form for the second search this
// time.
$this->submitGetForm('node', array('keys' => $this->randomMachineName(1)), t('Search'));
$this->drupalPostForm(NULL, array('keys' => $this->randomMachineName()), t('Search'), array(), array(), 'search-form');
$this->submitGetForm('node', ['keys' => $this->randomMachineName(1)], t('Search'));
$this->drupalPostForm(NULL, ['keys' => $this->randomMachineName()], t('Search'), [], [], 'search-form');
$this->assertNoText('You must include at least one keyword to match in the content', 'Keyword message is not displayed when searching for long word after short word search');
}
@@ -22,7 +22,7 @@ class SearchCommentTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('filter', 'node', 'comment');
public static $modules = ['filter', 'node', 'comment'];
/**
* Test subject for comments.
@@ -55,17 +55,17 @@ class SearchCommentTest extends SearchTestBase {
protected function setUp() {
parent::setUp();
$full_html_format = FilterFormat::create(array(
$full_html_format = FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
'weight' => 1,
'filters' => array(),
));
'filters' => [],
]);
$full_html_format->save();
// Create and log in an administrative user having access to the Full HTML
// text format.
$permissions = array(
$permissions = [
'administer filters',
$full_html_format->getPermissionName(),
'administer permissions',
@@ -73,7 +73,7 @@ class SearchCommentTest extends SearchTestBase {
'post comments',
'skip comment approval',
'access comments',
);
];
$this->adminUser = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->adminUser);
// Add a comment field.
@@ -83,18 +83,18 @@ class SearchCommentTest extends SearchTestBase {
/**
* Verify that comments are rendered using proper format in search results.
*/
function testSearchResultsComment() {
public function testSearchResultsComment() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
// Create basic_html format that escapes all HTML.
$basic_html_format = FilterFormat::create(array(
$basic_html_format = FilterFormat::create([
'format' => 'basic_html',
'name' => 'Basic HTML',
'weight' => 1,
'filters' => array(
'filter_html_escape' => array('status' => 1),
),
'roles' => array(RoleInterface::AUTHENTICATED_ID),
));
'filters' => [
'filter_html_escape' => ['status' => 1],
],
'roles' => [RoleInterface::AUTHENTICATED_ID],
]);
$basic_html_format->save();
$comment_body = 'Test comment body';
@@ -105,17 +105,17 @@ class SearchCommentTest extends SearchTestBase {
$field->save();
// Allow anonymous users to search content.
$edit = array(
$edit = [
RoleInterface::ANONYMOUS_ID . '[search content]' => 1,
RoleInterface::ANONYMOUS_ID . '[access comments]' => 1,
RoleInterface::ANONYMOUS_ID . '[post comments]' => 1,
);
];
$this->drupalPostForm('admin/people/permissions', $edit, t('Save permissions'));
// Create a node.
$node = $this->drupalCreateNode(array('type' => 'article'));
$node = $this->drupalCreateNode(['type' => 'article']);
// Post a comment using 'Full HTML' text format.
$edit_comment = array();
$edit_comment = [];
$edit_comment['subject[0][value]'] = 'Test comment subject';
$edit_comment['comment_body[0][value]'] = '<h1>' . $comment_body . '</h1>';
$full_html_format_id = 'full_html';
@@ -125,7 +125,7 @@ class SearchCommentTest extends SearchTestBase {
// Post a comment with an evil script tag in the comment subject and a
// script tag nearby a keyword in the comment body. Use the 'FULL HTML' text
// format so the script tag stored.
$edit_comment2 = array();
$edit_comment2 = [];
$edit_comment2['subject[0][value]'] = "<script>alert('subjectkeyword');</script>";
$edit_comment2['comment_body[0][value]'] = "nearbykeyword<script>alert('somethinggeneric');</script>";
$edit_comment2['comment_body[0][format]'] = $full_html_format_id;
@@ -133,7 +133,7 @@ class SearchCommentTest extends SearchTestBase {
// Post a comment with a keyword inside an evil script tag in the comment
// body. Use the 'FULL HTML' text format so the script tag is stored.
$edit_comment3 = array();
$edit_comment3 = [];
$edit_comment3['subject[0][value]'] = 'asubject';
$edit_comment3['comment_body[0][value]'] = "<script>alert('insidekeyword');</script>";
$edit_comment3['comment_body[0][format]'] = $full_html_format_id;
@@ -144,19 +144,19 @@ class SearchCommentTest extends SearchTestBase {
$this->cronRun();
// Search for the comment subject.
$edit = array(
$edit = [
'keys' => "'" . $edit_comment['subject[0][value]'] . "'",
);
];
$this->drupalPostForm('search/node', $edit, t('Search'));
$node_storage->resetCache(array($node->id()));
$node_storage->resetCache([$node->id()]);
$node2 = $node_storage->load($node->id());
$this->assertText($node2->label(), 'Node found in search results.');
$this->assertText($edit_comment['subject[0][value]'], 'Comment subject found in search results.');
// Search for the comment body.
$edit = array(
$edit = [
'keys' => "'" . $comment_body . "'",
);
];
$this->drupalPostForm(NULL, $edit, t('Search'));
$this->assertText($node2->label(), 'Node found in search results.');
@@ -166,9 +166,9 @@ class SearchCommentTest extends SearchTestBase {
$this->assertNoEscaped($edit_comment['comment_body[0][value]'], 'HTML in comment body is not escaped.');
// Search for the evil script comment subject.
$edit = array(
$edit = [
'keys' => 'subjectkeyword',
);
];
$this->drupalPostForm('search/node', $edit, t('Search'));
// Verify the evil comment subject is escaped in search results.
@@ -215,7 +215,7 @@ class SearchCommentTest extends SearchTestBase {
/**
* Verify access rules for comment indexing with different permissions.
*/
function testSearchResultsCommentAccess() {
public function testSearchResultsCommentAccess() {
$comment_body = 'Test comment body';
$this->commentSubject = 'Test comment subject';
$roles = $this->adminUser->getRoles(TRUE);
@@ -226,10 +226,10 @@ class SearchCommentTest extends SearchTestBase {
$field = FieldConfig::loadByName('node', 'article', 'comment');
$field->setSetting('preview', DRUPAL_OPTIONAL);
$field->save();
$this->node = $this->drupalCreateNode(array('type' => 'article'));
$this->node = $this->drupalCreateNode(['type' => 'article']);
// Post a comment using 'Full HTML' text format.
$edit_comment = array();
$edit_comment = [];
$edit_comment['subject[0][value]'] = $this->commentSubject;
$edit_comment['comment_body[0][value]'] = '<h1>' . $comment_body . '</h1>';
$this->drupalPostForm('comment/reply/node/' . $this->node->id() . '/comment', $edit_comment, t('Save'));
@@ -276,26 +276,26 @@ class SearchCommentTest extends SearchTestBase {
/**
* Set permissions for role.
*/
function setRolePermissions($rid, $access_comments = FALSE, $search_content = TRUE) {
$permissions = array(
public function setRolePermissions($rid, $access_comments = FALSE, $search_content = TRUE) {
$permissions = [
'access comments' => $access_comments,
'search content' => $search_content,
);
];
user_role_change_permissions($rid, $permissions);
}
/**
* Update search index and search for comment.
*/
function assertCommentAccess($assume_access, $message) {
public function assertCommentAccess($assume_access, $message) {
// Invoke search index update.
search_mark_for_reindex('node_search', $this->node->id());
$this->cronRun();
// Search for the comment subject.
$edit = array(
$edit = [
'keys' => "'" . $this->commentSubject . "'",
);
];
$this->drupalPostForm('search/node', $edit, t('Search'));
if ($assume_access) {
@@ -312,21 +312,21 @@ class SearchCommentTest extends SearchTestBase {
/**
* Verify that 'add new comment' does not appear in search results or index.
*/
function testAddNewComment() {
public function testAddNewComment() {
// Create a node with a short body.
$settings = array(
$settings = [
'type' => 'article',
'title' => 'short title',
'body' => array(array('value' => 'short body text')),
);
'body' => [['value' => 'short body text']],
];
$user = $this->drupalCreateUser(array(
$user = $this->drupalCreateUser([
'search content',
'create article content',
'access content',
'post comments',
'access comments',
));
]);
$this->drupalLogin($user);
$node = $this->drupalCreateNode($settings);
@@ -341,12 +341,12 @@ class SearchCommentTest extends SearchTestBase {
// Search for 'comment'. Should be no results.
$this->drupalLogin($user);
$this->drupalPostForm('search/node', array('keys' => 'comment'), t('Search'));
$this->drupalPostForm('search/node', ['keys' => 'comment'], t('Search'));
$this->assertText(t('Your search yielded no results'));
// Search for the node title. Should be found, and 'Add new comment' should
// not be part of the search snippet.
$this->drupalPostForm('search/node', array('keys' => 'short'), t('Search'));
$this->drupalPostForm('search/node', ['keys' => 'short'], t('Search'));
$this->assertText($node->label(), 'Search for keyword worked');
$this->assertNoText(t('Add new comment'));
}
@@ -3,6 +3,7 @@
namespace Drupal\search\Tests;
use Drupal\Core\Url;
use Drupal\search\Entity\SearchPage;
/**
* Verify the search config settings form.
@@ -16,7 +17,7 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('block', 'search_extra_type', 'test_page_test');
public static $modules = ['block', 'search_extra_type', 'test_page_test'];
/**
* User who can search and administer search.
@@ -36,7 +37,7 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
parent::setUp();
// Log in as a user that can create and search content.
$this->searchUser = $this->drupalCreateUser(array('search content', 'administer search', 'administer nodes', 'bypass node access', 'access user profiles', 'administer users', 'administer blocks', 'access site reports'));
$this->searchUser = $this->drupalCreateUser(['search content', 'administer search', 'administer nodes', 'bypass node access', 'access user profiles', 'administer users', 'administer blocks', 'access site reports']);
$this->drupalLogin($this->searchUser);
// Add a single piece of content and index it.
@@ -60,42 +61,42 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
/**
* Verifies the search settings form.
*/
function testSearchSettingsPage() {
public function testSearchSettingsPage() {
// Test that the settings form displays the correct count of items left to index.
$this->drupalGet('admin/config/search/pages');
$this->assertText(t('There are @count items left to index.', array('@count' => 0)));
$this->assertText(t('There are @count items left to index.', ['@count' => 0]));
// Test the re-index button.
$this->drupalPostForm('admin/config/search/pages', array(), t('Re-index site'));
$this->drupalPostForm('admin/config/search/pages', [], t('Re-index site'));
$this->assertText(t('Are you sure you want to re-index the site'));
$this->drupalPostForm('admin/config/search/pages/reindex', array(), t('Re-index site'));
$this->drupalPostForm('admin/config/search/pages/reindex', [], t('Re-index site'));
$this->assertText(t('All search indexes will be rebuilt'));
$this->drupalGet('admin/config/search/pages');
$this->assertText(t('There is 1 item left to index.'));
// Test that the form saves with the default values.
$this->drupalPostForm('admin/config/search/pages', array(), t('Save configuration'));
$this->drupalPostForm('admin/config/search/pages', [], t('Save configuration'));
$this->assertText(t('The configuration options have been saved.'), 'Form saves with the default values.');
// Test that the form does not save with an invalid word length.
$edit = array(
$edit = [
'minimum_word_size' => $this->randomMachineName(3),
);
];
$this->drupalPostForm('admin/config/search/pages', $edit, t('Save configuration'));
$this->assertNoText(t('The configuration options have been saved.'), 'Form does not save with an invalid word length.');
// Test logging setting. It should be off by default.
$text = $this->randomMachineName(5);
$this->drupalPostForm('search/node', array('keys' => $text), t('Search'));
$this->drupalPostForm('search/node', ['keys' => $text], t('Search'));
$this->drupalGet('admin/reports/dblog');
$this->assertNoLink('Searched Content for ' . $text . '.', 'Search was not logged');
// Turn on logging.
$edit = array('logging' => TRUE);
$edit = ['logging' => TRUE];
$this->drupalPostForm('admin/config/search/pages', $edit, t('Save configuration'));
$text = $this->randomMachineName(5);
$this->drupalPostForm('search/node', array('keys' => $text), t('Search'));
$this->drupalPostForm('search/node', ['keys' => $text], t('Search'));
$this->drupalGet('admin/reports/dblog');
$this->assertLink('Searched Content for ' . $text . '.', 0, 'Search was logged');
@@ -104,7 +105,7 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
/**
* Verifies plugin-supplied settings form.
*/
function testSearchModuleSettingsPage() {
public function testSearchModuleSettingsPage() {
$this->drupalGet('admin/config/search/pages');
$this->clickLink(t('Edit'), 1);
@@ -112,13 +113,13 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
$this->assertTrue($this->xpath('//select[@id="edit-extra-type-settings-boost"]//option[@value="bi" and @selected="selected"]'), 'Module specific settings are picked up from the default config');
// Change extra type setting and also modify a common search setting.
$edit = array(
$edit = [
'extra_type_settings[boost]' => 'ii',
);
];
$this->drupalPostForm(NULL, $edit, t('Save search page'));
// Ensure that the modifications took effect.
$this->assertRaw(t('The %label search page has been updated.', array('%label' => 'Dummy search type')));
$this->assertRaw(t('The %label search page has been updated.', ['%label' => 'Dummy search type']));
$this->drupalGet('admin/config/search/pages/manage/dummy_search_type');
$this->assertTrue($this->xpath('//select[@id="edit-extra-type-settings-boost"]//option[@value="ii" and @selected="selected"]'), 'Module specific settings can be changed');
}
@@ -126,26 +127,26 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
/**
* Verifies that you can disable individual search plugins.
*/
function testSearchModuleDisabling() {
public function testSearchModuleDisabling() {
// Array of search plugins to test: 'keys' are the keywords to search for,
// and 'text' is the text to assert is on the results page.
$plugin_info = array(
'node_search' => array(
$plugin_info = [
'node_search' => [
'keys' => 'pizza',
'text' => $this->searchNode->label(),
),
'user_search' => array(
],
'user_search' => [
'keys' => $this->searchUser->getUsername(),
'text' => $this->searchUser->getEmail(),
),
'dummy_search_type' => array(
],
'dummy_search_type' => [
'keys' => 'foo',
'text' => 'Dummy search snippet to display',
),
);
],
];
$plugins = array_keys($plugin_info);
/** @var $entities \Drupal\search\SearchPageInterface[] */
$entities = entity_load_multiple('search_page');
$entities = SearchPage::loadMultiple();
// Disable all of the search pages.
foreach ($entities as $entity) {
$entity->disable()->save();
@@ -153,12 +154,11 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
// Test each plugin if it's enabled as the only search plugin.
foreach ($entities as $entity_id => $entity) {
// Set this as default.
$this->drupalGet("admin/config/search/pages/manage/$entity_id/set-default");
$this->setDefaultThroughUi($entity_id);
// Run a search from the correct search URL.
$info = $plugin_info[$entity_id];
$this->drupalGet('search/' . $entity->getPath(), array('query' => array('keys' => $info['keys'])));
$this->drupalGet('search/' . $entity->getPath(), ['query' => ['keys' => $info['keys']]]);
$this->assertResponse(200);
$this->assertNoText('no results', $entity->label() . ' search found results');
$this->assertText($info['text'], 'Correct search text found');
@@ -173,10 +173,10 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
// Run a search from the search block on the node page. Verify you get
// to this plugin's search results page.
$terms = array('keys' => $info['keys']);
$terms = ['keys' => $info['keys']];
$this->submitGetForm('node', $terms, t('Search'));
$current = $this->getURL();
$expected = \Drupal::url('search.view_' . $entity->id(), array(), array('query' => array('keys' => $info['keys']), 'absolute' => TRUE));
$expected = \Drupal::url('search.view_' . $entity->id(), [], ['query' => ['keys' => $info['keys']], 'absolute' => TRUE]);
$this->assertEqual( $current, $expected, 'Block redirected to right search page');
// Try an invalid search path, which should 404.
@@ -186,24 +186,27 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
$entity->disable()->save();
}
// Set the node search as default.
$this->setDefaultThroughUi('node_search');
// Test with all search plugins enabled. When you go to the search
// page or run search, all plugins should be shown.
foreach ($entities as $entity) {
$entity->enable()->save();
}
// Set the node search as default.
$this->drupalGet('admin/config/search/pages/manage/node_search/set-default');
$paths = array(
array('path' => 'search/node', 'options' => array('query' => array('keys' => 'pizza'))),
array('path' => 'search/node', 'options' => array()),
);
\Drupal::service('router.builder')->rebuild();
$paths = [
['path' => 'search/node', 'options' => ['query' => ['keys' => 'pizza']]],
['path' => 'search/node', 'options' => []],
];
foreach ($paths as $item) {
$this->drupalGet($item['path'], $item['options']);
foreach ($plugins as $entity_id) {
$label = $entities[$entity_id]->label();
$this->assertText($label, format_string('%label search tab is shown', array('%label' => $label)));
$this->assertText($label, format_string('%label search tab is shown', ['%label' => $label]));
}
}
}
@@ -213,7 +216,7 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
*/
public function testDefaultSearchPageOrdering() {
$this->drupalGet('search');
$elements = $this->xpath('//*[contains(@class, :class)]//a', array(':class' => 'tabs primary'));
$elements = $this->xpath('//*[contains(@class, :class)]//a', [':class' => 'tabs primary']);
$this->assertIdentical((string) $elements[0]['href'], \Drupal::url('search.view_node_search'));
$this->assertIdentical((string) $elements[1]['href'], \Drupal::url('search.view_dummy_search_type'));
$this->assertIdentical((string) $elements[2]['href'], \Drupal::url('search.view_user_search'));
@@ -234,52 +237,52 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
$this->assertText(t('No search pages have been configured.'));
// Add a search page.
$edit = array();
$edit = [];
$edit['search_type'] = 'search_extra_type_search';
$this->drupalPostForm(NULL, $edit, t('Add new page'));
$this->drupalPostForm(NULL, $edit, t('Add search page'));
$this->assertTitle('Add new search page | Drupal');
$first = array();
$first = [];
$first['label'] = $this->randomString();
$first_id = $first['id'] = strtolower($this->randomMachineName(8));
$first['path'] = strtolower($this->randomMachineName(8));
$this->drupalPostForm(NULL, $first, t('Add search page'));
$this->drupalPostForm(NULL, $first, t('Save'));
$this->assertDefaultSearch($first_id, 'The default page matches the only search page.');
$this->assertRaw(t('The %label search page has been added.', array('%label' => $first['label'])));
$this->assertRaw(t('The %label search page has been added.', ['%label' => $first['label']]));
// Attempt to add a search page with an existing path.
$edit = array();
$edit = [];
$edit['search_type'] = 'search_extra_type_search';
$this->drupalPostForm(NULL, $edit, t('Add new page'));
$edit = array();
$this->drupalPostForm(NULL, $edit, t('Add search page'));
$edit = [];
$edit['label'] = $this->randomString();
$edit['id'] = strtolower($this->randomMachineName(8));
$edit['path'] = $first['path'];
$this->drupalPostForm(NULL, $edit, t('Add search page'));
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertText(t('The search page path must be unique.'));
// Add a second search page.
$second = array();
$second = [];
$second['label'] = $this->randomString();
$second_id = $second['id'] = strtolower($this->randomMachineName(8));
$second['path'] = strtolower($this->randomMachineName(8));
$this->drupalPostForm(NULL, $second, t('Add search page'));
$this->drupalPostForm(NULL, $second, t('Save'));
$this->assertDefaultSearch($first_id, 'The default page matches the only search page.');
// Ensure both search pages have their tabs displayed.
$this->drupalGet('search');
$elements = $this->xpath('//*[contains(@class, :class)]//a', array(':class' => 'tabs primary'));
$elements = $this->xpath('//*[contains(@class, :class)]//a', [':class' => 'tabs primary']);
$this->assertIdentical((string) $elements[0]['href'], Url::fromRoute('search.view_' . $first_id)->toString());
$this->assertIdentical((string) $elements[1]['href'], Url::fromRoute('search.view_' . $second_id)->toString());
// Switch the weight of the search pages and check the order of the tabs.
$edit = array(
$edit = [
'entities[' . $first_id . '][weight]' => 10,
'entities[' . $second_id . '][weight]' => -10,
);
];
$this->drupalPostForm('admin/config/search/pages', $edit, t('Save configuration'));
$this->drupalGet('search');
$elements = $this->xpath('//*[contains(@class, :class)]//a', array(':class' => 'tabs primary'));
$elements = $this->xpath('//*[contains(@class, :class)]//a', [':class' => 'tabs primary']);
$this->assertIdentical((string) $elements[0]['href'], Url::fromRoute('search.view_' . $second_id)->toString());
$this->assertIdentical((string) $elements[1]['href'], Url::fromRoute('search.view_' . $first_id)->toString());
@@ -290,7 +293,7 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
// Change the default search page.
$this->clickLink(t('Set as default'));
$this->assertRaw(t('The default search page is now %label. Be sure to check the ordering of your search pages.', array('%label' => $second['label'])));
$this->assertRaw(t('The default search page is now %label. Be sure to check the ordering of your search pages.', ['%label' => $second['label']]));
$this->verifySearchPageOperations($first_id, TRUE, TRUE, TRUE, FALSE);
$this->verifySearchPageOperations($second_id, TRUE, FALSE, FALSE, FALSE);
@@ -309,12 +312,25 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
// Test deleting.
$this->clickLink(t('Delete'));
$this->assertRaw(t('Are you sure you want to delete the search page %label?', array('%label' => $first['label'])));
$this->drupalPostForm(NULL, array(), t('Delete'));
$this->assertRaw(t('The search page %label has been deleted.', array('%label' => $first['label'])));
$this->assertRaw(t('Are you sure you want to delete the search page %label?', ['%label' => $first['label']]));
$this->drupalPostForm(NULL, [], t('Delete'));
$this->assertRaw(t('The search page %label has been deleted.', ['%label' => $first['label']]));
$this->verifySearchPageOperations($first_id, FALSE, FALSE, FALSE, FALSE);
}
/**
* Tests that the enable/disable/default routes are protected from CSRF.
*/
public function testRouteProtection() {
// Ensure that the enable and disable routes are protected.
$this->drupalGet('admin/config/search/pages/manage/node_search/enable');
$this->assertResponse(403);
$this->drupalGet('admin/config/search/pages/manage/node_search/disable');
$this->assertResponse(403);
$this->drupalGet('admin/config/search/pages/manage/node_search/set-default');
$this->assertResponse(403);
}
/**
* Checks that the search page operations match expectations.
*
@@ -372,4 +388,17 @@ class SearchConfigSettingsFormTest extends SearchTestBase {
$this->assertIdentical($search_page_repository->getDefaultSearchPage(), $expected, $message, $group);
}
/**
* Sets a search page as the default in the UI.
*
* @param string $entity_id
* The search page entity ID to enable.
*/
protected function setDefaultThroughUi($entity_id) {
$this->drupalGet('admin/config/search/pages');
preg_match('|href="([^"]+' . $entity_id . '/set-default[^"]+)"|', $this->getRawContent(), $matches);
$this->drupalGet($this->getAbsoluteUrl($matches[1]));
}
}
@@ -14,7 +14,7 @@ class SearchEmbedFormTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('search_embedded_form');
public static $modules = ['search_embedded_form'];
/**
* Node used for testing.
@@ -34,7 +34,7 @@ class SearchEmbedFormTest extends SearchTestBase {
parent::setUp();
// Create a user and a node, and update the search index.
$test_user = $this->drupalCreateUser(array('access content', 'search content', 'administer nodes'));
$test_user = $this->drupalCreateUser(['access content', 'search content', 'administer nodes']);
$this->drupalLogin($test_user);
$this->node = $this->drupalCreateNode();
@@ -50,10 +50,10 @@ class SearchEmbedFormTest extends SearchTestBase {
/**
* Tests that the embedded form appears and can be submitted.
*/
function testEmbeddedForm() {
public function testEmbeddedForm() {
// First verify we can submit the form from the module's page.
$this->drupalPostForm('search_embedded_form',
array('name' => 'John'),
['name' => 'John'],
t('Send away'));
$this->assertText(t('Test form was submitted'), 'Form message appears');
$count = \Drupal::state()->get('search_embedded_form.submit_count');
@@ -61,10 +61,10 @@ class SearchEmbedFormTest extends SearchTestBase {
$this->submitCount = $count;
// Now verify that we can see and submit the form from the search results.
$this->drupalGet('search/node', array('query' => array('keys' => $this->node->label())));
$this->drupalGet('search/node', ['query' => ['keys' => $this->node->label()]]);
$this->assertText(t('Your name'), 'Form is visible');
$this->drupalPostForm(NULL,
array('name' => 'John'),
['name' => 'John'],
t('Send away'));
$this->assertText(t('Test form was submitted'), 'Form message appears');
$count = \Drupal::state()->get('search_embedded_form.submit_count');
@@ -74,7 +74,7 @@ class SearchEmbedFormTest extends SearchTestBase {
// Now verify that if we submit the search form, it doesn't count as
// our form being submitted.
$this->drupalPostForm('search',
array('keys' => 'foo'),
['keys' => 'foo'],
t('Search'));
$this->assertNoText(t('Test form was submitted'), 'Form message does not appear');
$count = \Drupal::state()->get('search_embedded_form.submit_count');
@@ -17,7 +17,7 @@ class SearchLanguageTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('language');
public static $modules = ['language'];
/**
* Array of nodes available to search.
@@ -30,7 +30,7 @@ class SearchLanguageTest extends SearchTestBase {
parent::setUp();
// Create and log in user.
$test_user = $this->drupalCreateUser(array('access content', 'search content', 'use advanced search', 'administer nodes', 'administer languages', 'access administration pages', 'administer site configuration'));
$test_user = $this->drupalCreateUser(['access content', 'search content', 'use advanced search', 'administer nodes', 'administer languages', 'access administration pages', 'administer site configuration']);
$this->drupalLogin($test_user);
// Add a new language.
@@ -45,38 +45,38 @@ class SearchLanguageTest extends SearchTestBase {
// Create a few page nodes with multilingual body values.
$default_format = filter_default_format();
$nodes = array(
array(
$nodes = [
[
'title' => 'First node en',
'type' => 'page',
'body' => array(array('value' => $this->randomMachineName(32), 'format' => $default_format)),
'body' => [['value' => $this->randomMachineName(32), 'format' => $default_format]],
'langcode' => 'en',
),
array(
],
[
'title' => 'Second node this is the Spanish title',
'type' => 'page',
'body' => array(array('value' => $this->randomMachineName(32), 'format' => $default_format)),
'body' => [['value' => $this->randomMachineName(32), 'format' => $default_format]],
'langcode' => 'es',
),
array(
],
[
'title' => 'Third node en',
'type' => 'page',
'body' => array(array('value' => $this->randomMachineName(32), 'format' => $default_format)),
'body' => [['value' => $this->randomMachineName(32), 'format' => $default_format]],
'langcode' => 'en',
),
);
],
];
$this->searchableNodes = [];
foreach ($nodes as $setting) {
$this->searchableNodes[] = $this->drupalCreateNode($setting);
}
// Add English translation to the second node.
$translation = $this->searchableNodes[1]->addTranslation('en', array('title' => 'Second node en'));
$translation = $this->searchableNodes[1]->addTranslation('en', ['title' => 'Second node en']);
$translation->body->value = $this->randomMachineName(32);
$this->searchableNodes[1]->save();
// Add Spanish translation to the third node.
$translation = $this->searchableNodes[2]->addTranslation('es', array('title' => 'Third node es'));
$translation = $this->searchableNodes[2]->addTranslation('es', ['title' => 'Third node es']);
$translation->body->value = $this->randomMachineName(32);
$this->searchableNodes[2]->save();
@@ -86,9 +86,9 @@ class SearchLanguageTest extends SearchTestBase {
search_update_totals();
}
function testLanguages() {
public function testLanguages() {
// Add predefined language.
$edit = array('predefined_langcode' => 'fr');
$edit = ['predefined_langcode' => 'fr'];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
$this->assertText('French', 'Language added successfully.');
@@ -99,11 +99,11 @@ class SearchLanguageTest extends SearchTestBase {
$this->assertText(t('French'), 'French is a possible choice.');
// Ensure selecting no language does not make the query different.
$this->drupalPostForm('search/node', array(), t('Advanced search'));
$this->drupalPostForm('search/node', [], t('Advanced search'));
$this->assertUrl(\Drupal::url('search.view_node_search', [], ['query' => ['keys' => ''], 'absolute' => TRUE]), [], 'Correct page redirection, no language filtering.');
// Pick French and ensure it is selected.
$edit = array('language[fr]' => TRUE);
$edit = ['language[fr]' => TRUE];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
// Get the redirected URL.
$url = $this->getUrl();
@@ -112,7 +112,7 @@ class SearchLanguageTest extends SearchTestBase {
$this->assertTrue(strpos($query_string, '=language:fr') !== FALSE, 'Language filter language:fr add to the query string.');
// Search for keyword node and language filter as Spanish.
$edit = array('keys' => 'node', 'language[es]' => TRUE);
$edit = ['keys' => 'node', 'language[es]' => TRUE];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
// Check for Spanish results.
$this->assertLink('Second node this is the Spanish title', 0, 'Second node Spanish title found in search results');
@@ -126,12 +126,12 @@ class SearchLanguageTest extends SearchTestBase {
$path = 'admin/config/regional/language';
$this->drupalGet($path);
$this->assertFieldChecked('edit-site-default-language-en', 'Default language updated.');
$edit = array(
$edit = [
'site_default_language' => 'fr',
);
];
$this->drupalPostForm($path, $edit, t('Save configuration'));
$this->assertNoFieldChecked('edit-site-default-language-en', 'Default language updated.');
$this->drupalPostForm('admin/config/regional/language/delete/en', array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete'));
}
}
@@ -14,7 +14,7 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array();
public static $modules = [];
/**
* A user with permission to access and search content.
@@ -27,19 +27,19 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
parent::setUp();
// Create a test user and log in.
$this->testUser = $this->drupalCreateUser(array('access content', 'search content'));
$this->testUser = $this->drupalCreateUser(['access content', 'search content']);
$this->drupalLogin($this->testUser);
}
/**
* Tests that the search index info is properly updated when a node changes.
*/
function testSearchIndexUpdateOnNodeChange() {
public function testSearchIndexUpdateOnNodeChange() {
// Create a node.
$node = $this->drupalCreateNode(array(
$node = $this->drupalCreateNode([
'title' => 'Someone who says Ni!',
'body' => array(array('value' => "We are the knights who say Ni!")),
'type' => 'page'));
'body' => [['value' => "We are the knights who say Ni!"]],
'type' => 'page']);
$node_search_plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
// Update the search index.
@@ -47,7 +47,7 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
search_update_totals();
// Search the node to verify it appears in search results
$edit = array('keys' => 'knights');
$edit = ['keys' => 'knights'];
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText($node->label());
@@ -60,7 +60,7 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
search_update_totals();
// Search again to verify the new text appears in test results.
$edit = array('keys' => 'shrubbery');
$edit = ['keys' => 'shrubbery'];
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText($node->label());
}
@@ -68,12 +68,12 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
/**
* Tests that the search index info is updated when a node is deleted.
*/
function testSearchIndexUpdateOnNodeDeletion() {
public function testSearchIndexUpdateOnNodeDeletion() {
// Create a node.
$node = $this->drupalCreateNode(array(
$node = $this->drupalCreateNode([
'title' => 'No dragons here',
'body' => array(array('value' => 'Again: No dragons here')),
'type' => 'page'));
'body' => [['value' => 'Again: No dragons here']],
'type' => 'page']);
$node_search_plugin = $this->container->get('plugin.manager.search')->createInstance('node_search');
// Update the search index.
@@ -81,12 +81,12 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
search_update_totals();
// Search the node to verify it appears in search results
$edit = array('keys' => 'dragons');
$edit = ['keys' => 'dragons'];
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText($node->label());
// Get the node info from the search index tables.
$search_index_dataset = db_query("SELECT sid FROM {search_index} WHERE type = 'node_search' AND word = :word", array(':word' => 'dragons'))
$search_index_dataset = db_query("SELECT sid FROM {search_index} WHERE type = 'node_search' AND word = :word", [':word' => 'dragons'])
->fetchField();
$this->assertNotEqual($search_index_dataset, FALSE, t('Node info found on the search_index'));
@@ -94,7 +94,7 @@ class SearchNodeUpdateAndDeletionTest extends SearchTestBase {
$node->delete();
// Check if the node info is gone from the search table.
$search_index_dataset = db_query("SELECT sid FROM {search_index} WHERE type = 'node_search' AND word = :word", array(':word' => 'dragons'))
$search_index_dataset = db_query("SELECT sid FROM {search_index} WHERE type = 'node_search' AND word = :word", [':word' => 'dragons'])
->fetchField();
$this->assertFalse($search_index_dataset, t('Node info successfully removed from search_index'));
@@ -27,7 +27,7 @@ class SearchNumberMatchingTest extends SearchTestBase {
*
* @var string[]
*/
protected $numbers = array(
protected $numbers = [
'123456789',
'12/34/56789',
'12.3456789',
@@ -35,7 +35,7 @@ class SearchNumberMatchingTest extends SearchTestBase {
'123,456,789',
'-123456789',
'0123456789',
);
];
/**
* An array of nodes created for testing purposes.
@@ -47,15 +47,15 @@ class SearchNumberMatchingTest extends SearchTestBase {
protected function setUp() {
parent::setUp();
$this->testUser = $this->drupalCreateUser(array('search content', 'access content', 'administer nodes', 'access site reports'));
$this->testUser = $this->drupalCreateUser(['search content', 'access content', 'administer nodes', 'access site reports']);
$this->drupalLogin($this->testUser);
foreach ($this->numbers as $num) {
$info = array(
'body' => array(array('value' => $num)),
$info = [
'body' => [['value' => $num]],
'type' => 'page',
'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
);
];
$this->nodes[] = $this->drupalCreateNode($info);
}
@@ -68,16 +68,16 @@ class SearchNumberMatchingTest extends SearchTestBase {
/**
* Tests that all the numbers can be searched.
*/
function testNumberSearching() {
public function testNumberSearching() {
for ($i = 0; $i < count($this->numbers); $i++) {
$node = $this->nodes[$i];
// Verify that the node title does not appear on the search page
// with a dummy search.
$this->drupalPostForm('search/node',
array('keys' => 'foo'),
['keys' => 'foo'],
t('Search'));
$this->assertNoText($node->label(), format_string('%number: node title not shown in dummy search', array('%number' => $i)));
$this->assertNoText($node->label(), format_string('%number: node title not shown in dummy search', ['%number' => $i]));
// Now verify that we can find node i by searching for any of the
// numbers.
@@ -88,9 +88,9 @@ class SearchNumberMatchingTest extends SearchTestBase {
$number = ltrim($number, '-');
$this->drupalPostForm('search/node',
array('keys' => $number),
['keys' => $number],
t('Search'));
$this->assertText($node->label(), format_string('%i: node title shown (search found the node) in search for number %number', array('%i' => $i, '%number' => $number)));
$this->assertText($node->label(), format_string('%i: node title shown (search found the node) in search for number %number', ['%i' => $i, '%number' => $number]));
}
}
@@ -26,7 +26,7 @@ class SearchNumbersTest extends SearchTestBase {
*
* @var string[]
*/
protected $numbers = array(
protected $numbers = [
'ISBN' => '978-0446365383',
'UPC' => '036000 291452',
'EAN bar code' => '5901234123457',
@@ -41,7 +41,7 @@ class SearchNumbersTest extends SearchTestBase {
'over fifty characters' => '666666666666666666666666666666666666666666666666666666666666',
'date' => '01/02/2009',
'commas' => '987,654,321',
);
];
/**
* An array of nodes created for testing purposes.
@@ -53,16 +53,16 @@ class SearchNumbersTest extends SearchTestBase {
protected function setUp() {
parent::setUp();
$this->testUser = $this->drupalCreateUser(array('search content', 'access content', 'administer nodes', 'access site reports'));
$this->testUser = $this->drupalCreateUser(['search content', 'access content', 'administer nodes', 'access site reports']);
$this->drupalLogin($this->testUser);
foreach ($this->numbers as $doc => $num) {
$info = array(
'body' => array(array('value' => $num)),
$info = [
'body' => [['value' => $num]],
'type' => 'page',
'language' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'title' => $doc . ' number',
);
];
$this->nodes[$doc] = $this->drupalCreateNode($info);
}
@@ -75,7 +75,7 @@ class SearchNumbersTest extends SearchTestBase {
/**
* Tests that all the numbers can be searched.
*/
function testNumberSearching() {
public function testNumberSearching() {
$types = array_keys($this->numbers);
foreach ($types as $type) {
@@ -88,16 +88,16 @@ class SearchNumbersTest extends SearchTestBase {
// Verify that the node title does not appear on the search page
// with a dummy search.
$this->drupalPostForm('search/node',
array('keys' => 'foo'),
['keys' => 'foo'],
t('Search'));
$this->assertNoText($node->label(), $type . ': node title not shown in dummy search');
// Verify that the node title does appear as a link on the search page
// when searching for the number.
$this->drupalPostForm('search/node',
array('keys' => $number),
['keys' => $number],
t('Search'));
$this->assertText($node->label(), format_string('%type: node title shown (search found the node) in search for number %number.', array('%type' => $type, '%number' => $number)));
$this->assertText($node->label(), format_string('%type: node title shown (search found the node) in search for number %number.', ['%type' => $type, '%number' => $number]));
}
}
@@ -37,7 +37,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
parent::setUp();
// Create user.
$this->searchingUser = $this->drupalCreateUser(array('search content', 'access user profiles'));
$this->searchingUser = $this->drupalCreateUser(['search content', 'access user profiles']);
// Create a node and update the search index.
$this->node = $this->drupalCreateNode(['title' => 'bike shed shop']);
@@ -50,7 +50,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
/**
* Tests the presence of the expected cache tag in various situations.
*/
function testSearchText() {
public function testSearchText() {
$this->drupalLogin($this->searchingUser);
// Initial page for searching nodes.
@@ -60,7 +60,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
$this->assertCacheTag('node_list');
// Node search results.
$edit = array();
$edit = [];
$edit['keys'] = 'bike shed';
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText('bike shed shop');
@@ -70,6 +70,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
$this->assertCacheTag('node:1');
$this->assertCacheTag('user:2');
$this->assertCacheTag('rendered');
$this->assertCacheTag('http_response');
$this->assertCacheTag('node_list');
// Updating a node should invalidate the search plugin's index cache tag.
@@ -83,6 +84,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
$this->assertCacheTag('node:1');
$this->assertCacheTag('user:2');
$this->assertCacheTag('rendered');
$this->assertCacheTag('http_response');
$this->assertCacheTag('node_list');
// Deleting a node should invalidate the search plugin's index cache tag.
@@ -172,6 +174,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
'config:search.page.node_search',
'search_index',
'search_index:node_search',
'http_response',
'rendered',
'node_list',
];
@@ -179,7 +182,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
// Node search results for shop, should return node:1 (bike shed shop) and
// node:2 (Llama shop). The related authors cache tags should be visible as
// well.
$edit = array();
$edit = [];
$edit['keys'] = 'shop';
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText('bike shed shop');
@@ -192,13 +195,12 @@ class SearchPageCacheTagsTest extends SearchTestBase {
'node_view',
'config:filter.format.plain_text',
]);
$cache_tags = $this->drupalGetHeader('X-Drupal-Cache-Tags');
$this->assertEqual(explode(' ', $cache_tags), $expected_cache_tags);
$this->assertCacheTags($expected_cache_tags);
// Only get the new node in the search results, should result in node:1,
// node:2 and user:3 as cache tags even though only node:1 is shown. This is
// because node:2 is reference in node:1 as an entity reference.
$edit = array();
$edit = [];
$edit['keys'] = 'Llama';
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText('Llama shop');
@@ -208,8 +210,7 @@ class SearchPageCacheTagsTest extends SearchTestBase {
'user:3',
'node_view',
]);
$cache_tags = $this->drupalGetHeader('X-Drupal-Cache-Tags');
$this->assertEqual(explode(' ', $cache_tags), $expected_cache_tags);
$this->assertCacheTags($expected_cache_tags);
}
}
@@ -32,7 +32,7 @@ class SearchPageTextTest extends SearchTestBase {
parent::setUp();
// Create user.
$this->searchingUser = $this->drupalCreateUser(array('search content', 'access user profiles', 'use advanced search'));
$this->searchingUser = $this->drupalCreateUser(['search content', 'access user profiles', 'use advanced search']);
$this->drupalPlaceBlock('local_tasks_block');
$this->drupalPlaceBlock('page_title_block');
}
@@ -42,8 +42,8 @@ class SearchPageTextTest extends SearchTestBase {
*
* This is a regression test for https://www.drupal.org/node/2338081
*/
function testSearchLabelXSS() {
$this->drupalLogin($this->drupalCreateUser(array('administer search')));
public function testSearchLabelXSS() {
$this->drupalLogin($this->drupalCreateUser(['administer search']));
$keys['label'] = '<script>alert("Dont Panic");</script>';
$this->drupalPostForm('admin/config/search/pages/manage/node_search', $keys, t('Save search page'));
@@ -56,21 +56,21 @@ class SearchPageTextTest extends SearchTestBase {
/**
* Tests the failed search text, and various other text on the search page.
*/
function testSearchText() {
public function testSearchText() {
$this->drupalLogin($this->searchingUser);
$this->drupalGet('search/node');
$this->assertText(t('Enter your keywords'));
$this->assertText(t('Search'));
$this->assertTitle(t('Search') . ' | Drupal', 'Search page title is correct');
$edit = array();
$edit = [];
$search_terms = 'bike shed ' . $this->randomMachineName();
$edit['keys'] = $search_terms;
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertText('search yielded no results');
$this->assertText(t('Search'));
$title_source = 'Search for @keywords | Drupal';
$this->assertTitle(t($title_source, array('@keywords' => Unicode::truncate($search_terms, 60, TRUE, TRUE))), 'Search page title is correct');
$this->assertTitle(t($title_source, ['@keywords' => Unicode::truncate($search_terms, 60, TRUE, TRUE)]), 'Search page title is correct');
$this->assertNoText('Node', 'Erroneous tab and breadcrumb text is not present');
$this->assertNoText(t('Node'), 'Erroneous translated tab and breadcrumb text is not present');
$this->assertText(t('Content'), 'Tab and breadcrumb text is present');
@@ -80,23 +80,23 @@ class SearchPageTextTest extends SearchTestBase {
$this->assertText('Use upper-case OR to get more results', 'Correct text is on content search help page');
// Search for a longer text, and see that it is in the title, truncated.
$edit = array();
$edit = [];
$search_terms = 'Every word is like an unnecessary stain on silence and nothingness.';
$edit['keys'] = $search_terms;
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertTitle(t($title_source, array('@keywords' => 'Every word is like an unnecessary stain on silence and…')), 'Search page title is correct');
$this->assertTitle(t($title_source, ['@keywords' => 'Every word is like an unnecessary stain on silence and…']), 'Search page title is correct');
// Search for a string with a lot of special characters.
$search_terms = 'Hear nothing > "see nothing" `feel' . " '1982.";
$edit['keys'] = $search_terms;
$this->drupalPostForm('search/node', $edit, t('Search'));
$actual_title = (string) current($this->xpath('//title'));
$this->assertEqual($actual_title, Html::decodeEntities(t($title_source, array('@keywords' => Unicode::truncate($search_terms, 60, TRUE, TRUE)))), 'Search page title is correct');
$this->assertEqual($actual_title, Html::decodeEntities(t($title_source, ['@keywords' => Unicode::truncate($search_terms, 60, TRUE, TRUE)])), 'Search page title is correct');
$edit['keys'] = $this->searchingUser->getUsername();
$this->drupalPostForm('search/user', $edit, t('Search'));
$this->assertText(t('Search'));
$this->assertTitle(t($title_source, array('@keywords' => Unicode::truncate($this->searchingUser->getUsername(), 60, TRUE, TRUE))));
$this->assertTitle(t($title_source, ['@keywords' => Unicode::truncate($this->searchingUser->getUsername(), 60, TRUE, TRUE)]));
$this->clickLink('Search help');
$this->assertText('Search help', 'Correct title is on search help page');
@@ -105,14 +105,14 @@ class SearchPageTextTest extends SearchTestBase {
// Test that search keywords containing slashes are correctly loaded
// from the GET params and displayed in the search form.
$arg = $this->randomMachineName() . '/' . $this->randomMachineName();
$this->drupalGet('search/node', array('query' => array('keys' => $arg)));
$this->drupalGet('search/node', ['query' => ['keys' => $arg]]);
$input = $this->xpath("//input[@id='edit-keys' and @value='{$arg}']");
$this->assertFalse(empty($input), 'Search keys with a / are correctly set as the default value in the search box.');
// Test a search input exceeding the limit of AND/OR combinations to test
// the Denial-of-Service protection.
$limit = $this->config('search.settings')->get('and_or_limit');
$keys = array();
$keys = [];
for ($i = 0; $i < $limit + 1; $i++) {
// Use a key of 4 characters to ensure we never generate 'AND' or 'OR'.
$keys[] = $this->randomMachineName(4);
@@ -122,40 +122,40 @@ class SearchPageTextTest extends SearchTestBase {
}
$edit['keys'] = implode(' ', $keys);
$this->drupalPostForm('search/node', $edit, t('Search'));
$this->assertRaw(t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => $limit)));
$this->assertRaw(t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', ['@count' => $limit]));
// Test that a search on Node or User with no keywords entered generates
// the "Please enter some keywords" message.
$this->drupalPostForm('search/node', array(), t('Search'));
$this->drupalPostForm('search/node', [], t('Search'));
$this->assertText(t('Please enter some keywords'), 'With no keywords entered, message is displayed on node page');
$this->drupalPostForm('search/user', array(), t('Search'));
$this->drupalPostForm('search/user', [], t('Search'));
$this->assertText(t('Please enter some keywords'), 'With no keywords entered, message is displayed on user page');
// Make sure the "Please enter some keywords" message is NOT displayed if
// you use "or" words or phrases in Advanced Search.
$this->drupalPostForm('search/node', array('or' => $this->randomMachineName() . ' ' . $this->randomMachineName()), t('Advanced search'));
$this->drupalPostForm('search/node', ['or' => $this->randomMachineName() . ' ' . $this->randomMachineName()], t('Advanced search'));
$this->assertNoText(t('Please enter some keywords'), 'With advanced OR keywords entered, no keywords message is not displayed on node page');
$this->drupalPostForm('search/node', array('phrase' => '"' . $this->randomMachineName() . '" "' . $this->randomMachineName() . '"'), t('Advanced search'));
$this->drupalPostForm('search/node', ['phrase' => '"' . $this->randomMachineName() . '" "' . $this->randomMachineName() . '"'], t('Advanced search'));
$this->assertNoText(t('Please enter some keywords'), 'With advanced phrase entered, no keywords message is not displayed on node page');
// Verify that if you search for a too-short keyword, you get the right
// message, and that if after that you search for a longer keyword, you
// do not still see the message.
$this->drupalPostForm('search/node', array('keys' => $this->randomMachineName(1)), t('Search'));
$this->drupalPostForm('search/node', ['keys' => $this->randomMachineName(1)], t('Search'));
$this->assertText('You must include at least one keyword', 'Keyword message is displayed when searching for short word');
$this->assertNoText(t('Please enter some keywords'), 'With short word entered, no keywords message is not displayed');
$this->drupalPostForm(NULL, array('keys' => $this->randomMachineName()), t('Search'));
$this->drupalPostForm(NULL, ['keys' => $this->randomMachineName()], t('Search'));
$this->assertNoText('You must include at least one keyword', 'Keyword message is not displayed when searching for long word after short word search');
// Test that if you search for a URL with .. in it, you still end up at
// the search page. See issue https://www.drupal.org/node/890058.
$this->drupalPostForm('search/node', array('keys' => '../../admin'), t('Search'));
$this->drupalPostForm('search/node', ['keys' => '../../admin'], t('Search'));
$this->assertResponse(200, 'Searching for ../../admin with non-admin user does not lead to a 403 error');
$this->assertText('no results', 'Searching for ../../admin with non-admin user gives you a no search results page');
// Test that if you search for a URL starting with "./", you still end up
// at the search page. See issue https://www.drupal.org/node/1421560.
$this->drupalPostForm('search/node', array('keys' => '.something'), t('Search'));
$this->drupalPostForm('search/node', ['keys' => '.something'], t('Search'));
$this->assertResponse(200, 'Searching for .something does not lead to a 403 error');
$this->assertText('no results', 'Searching for .something gives you a no search results page');
}
@@ -14,7 +14,7 @@ class SearchPreprocessLangcodeTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('search_langcode_test');
public static $modules = ['search_langcode_test'];
/**
* Test node for searching.
@@ -26,21 +26,21 @@ class SearchPreprocessLangcodeTest extends SearchTestBase {
protected function setUp() {
parent::setUp();
$web_user = $this->drupalCreateUser(array(
$web_user = $this->drupalCreateUser([
'create page content',
'edit own page content',
'search content',
'use advanced search',
));
]);
$this->drupalLogin($web_user);
}
/**
* Tests that hook_search_preprocess() returns the correct langcode.
*/
function testPreprocessLangcode() {
public function testPreprocessLangcode() {
// Create a node.
$this->node = $this->drupalCreateNode(array('body' => array(array()), 'langcode' => 'en'));
$this->node = $this->drupalCreateNode(['body' => [[]], 'langcode' => 'en']);
// First update the index. This does the initial processing.
$this->container->get('plugin.manager.search')->createInstance('node_search')->updateIndex();
@@ -53,7 +53,7 @@ class SearchPreprocessLangcodeTest extends SearchTestBase {
// Search for the additional text that is added by the preprocess
// function. If you search for text that is in the node, preprocess is
// not invoked on the node during the search excerpt generation.
$edit = array('or' => 'Additional text');
$edit = ['or' => 'Additional text'];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
// Checks if the langcode message has been set by hook_search_preprocess().
@@ -63,13 +63,13 @@ class SearchPreprocessLangcodeTest extends SearchTestBase {
/**
* Tests stemming for hook_search_preprocess().
*/
function testPreprocessStemming() {
public function testPreprocessStemming() {
// Create a node.
$this->node = $this->drupalCreateNode(array(
$this->node = $this->drupalCreateNode([
'title' => 'we are testing',
'body' => array(array()),
'body' => [[]],
'langcode' => 'en',
));
]);
// First update the index. This does the initial processing.
$this->container->get('plugin.manager.search')->createInstance('node_search')->updateIndex();
@@ -80,7 +80,7 @@ class SearchPreprocessLangcodeTest extends SearchTestBase {
search_update_totals();
// Search for the title of the node with a POST query.
$edit = array('or' => 'testing');
$edit = ['or' => 'testing'];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
// Check if the node has been found.
@@ -88,7 +88,7 @@ class SearchPreprocessLangcodeTest extends SearchTestBase {
$this->assertText('we are testing');
// Search for the same node using a different query.
$edit = array('or' => 'test');
$edit = ['or' => 'test'];
$this->drupalPostForm('search/node', $edit, t('Advanced search'));
// Check if the node has been found.
@@ -13,22 +13,22 @@ class SearchQueryAlterTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('search_query_alter');
public static $modules = ['search_query_alter'];
/**
* Tests that the query alter works.
*/
function testQueryAlter() {
public function testQueryAlter() {
// Log in with sufficient privileges.
$this->drupalLogin($this->drupalCreateUser(array('create page content', 'search content')));
$this->drupalLogin($this->drupalCreateUser(['create page content', 'search content']));
// Create a node and an article with the same keyword. The query alter
// test module will alter the query so only articles should be returned.
$data = array(
$data = [
'type' => 'page',
'title' => 'test page',
'body' => array(array('value' => 'pizza')),
);
'body' => [['value' => 'pizza']],
];
$this->drupalCreateNode($data);
$data['type'] = 'article';
@@ -40,7 +40,7 @@ class SearchQueryAlterTest extends SearchTestBase {
search_update_totals();
// Search for the body keyword 'pizza'.
$this->drupalPostForm('search/node', array('keys' => 'pizza'), t('Search'));
$this->drupalPostForm('search/node', ['keys' => 'pizza'], t('Search'));
// The article should be there but not the page.
$this->assertText('article', 'Article is in search results');
$this->assertNoText('page', 'Page is not in search results');
@@ -6,6 +6,7 @@ use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\Core\Url;
use Drupal\filter\Entity\FilterFormat;
use Drupal\search\Entity\SearchPage;
/**
* Indexes content and tests ranking factors.
@@ -28,16 +29,16 @@ class SearchRankingTest extends SearchTestBase {
*
* @var array
*/
public static $modules = array('statistics', 'comment');
public static $modules = ['statistics', 'comment'];
protected function setUp() {
parent::setUp();
// Create a plugin instance.
$this->nodeSearch = entity_load('search_page', 'node_search');
$this->nodeSearch = SearchPage::load('node_search');
// Log in with sufficient privileges.
$this->drupalLogin($this->drupalCreateUser(array('post comments', 'skip comment approval', 'create page content', 'administer search')));
$this->drupalLogin($this->drupalCreateUser(['post comments', 'skip comment approval', 'create page content', 'administer search']));
}
public function testRankings() {
@@ -45,24 +46,24 @@ class SearchRankingTest extends SearchTestBase {
$this->addDefaultCommentField('node', 'page');
// Build a list of the rankings to test.
$node_ranks = array('sticky', 'promote', 'relevance', 'recent', 'comments', 'views');
$node_ranks = ['sticky', 'promote', 'relevance', 'recent', 'comments', 'views'];
// Create nodes for testing.
$nodes = array();
$nodes = [];
foreach ($node_ranks as $node_rank) {
$settings = array(
$settings = [
'type' => 'page',
'comment' => array(array(
'comment' => [[
'status' => CommentItemInterface::HIDDEN,
)),
]],
'title' => 'Drupal rocks',
'body' => array(array('value' => "Drupal's search rocks")),
'body' => [['value' => "Drupal's search rocks"]],
// Node is one day old.
'created' => REQUEST_TIME - 24 * 3600,
'sticky' => 0,
'promote' => 0,
);
foreach (array(0, 1) as $num) {
];
foreach ([0, 1] as $num) {
if ($num == 1) {
switch ($node_rank) {
case 'sticky':
@@ -86,7 +87,7 @@ class SearchRankingTest extends SearchTestBase {
}
// Add a comment to one of the nodes.
$edit = array();
$edit = [];
$edit['subject[0][value]'] = 'my comment title';
$edit['comment_body[0][value]'] = 'some random comment';
$this->drupalGet('comment/reply/node/' . $nodes['comments'][1]->id() . '/comment');
@@ -101,7 +102,7 @@ class SearchRankingTest extends SearchTestBase {
// counter for this node.
$nid = $nodes['views'][1]->id();
db_insert('node_counter')
->fields(array('totalcount' => 5, 'daycount' => 5, 'timestamp' => REQUEST_TIME, 'nid' => $nid))
->fields(['totalcount' => 5, 'daycount' => 5, 'timestamp' => REQUEST_TIME, 'nid' => $nid])
->execute();
// Run cron to update the search index and comment/statistics totals.
@@ -117,7 +118,7 @@ class SearchRankingTest extends SearchTestBase {
}
// Test each of the possible rankings.
$edit = array();
$edit = [];
foreach ($node_ranks as $node_rank) {
// Enable the ranking we are testing.
$edit['rankings[' . $node_rank . '][value]'] = 10;
@@ -126,9 +127,9 @@ class SearchRankingTest extends SearchTestBase {
$this->assertTrue($this->xpath('//select[@id="edit-rankings-' . $node_rank . '-value"]//option[@value="10"]'), 'Select list to prioritize ' . $node_rank . ' for node ranks is visible and set to 10.');
// Reload the plugin to get the up-to-date values.
$this->nodeSearch = entity_load('search_page', 'node_search');
$this->nodeSearch = SearchPage::load('node_search');
// Do the search and assert the results.
$this->nodeSearch->getPlugin()->setSearch('rocks', array(), array());
$this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
$set = $this->nodeSearch->getPlugin()->execute();
$this->assertEqual($set[0]['node']->id(), $nodes[$node_rank][1]->id(), 'Search ranking "' . $node_rank . '" order.');
@@ -146,14 +147,14 @@ class SearchRankingTest extends SearchTestBase {
// Try with sticky, then promoted. This is a test for issue
// https://www.drupal.org/node/771596.
$node_ranks = array(
$node_ranks = [
'sticky' => 10,
'promote' => 1,
'relevance' => 0,
'recent' => 0,
'comments' => 0,
'views' => 0,
);
];
$configuration = $this->nodeSearch->getPlugin()->getConfiguration();
foreach ($node_ranks as $var => $value) {
$configuration['rankings'][$var] = $value;
@@ -163,7 +164,7 @@ class SearchRankingTest extends SearchTestBase {
// Do the search and assert the results. The sticky node should show up
// first, then the promoted node, then all the rest.
$this->nodeSearch->getPlugin()->setSearch('rocks', array(), array());
$this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
$set = $this->nodeSearch->getPlugin()->execute();
$this->assertEqual($set[0]['node']->id(), $nodes['sticky'][1]->id(), 'Search ranking for sticky first worked.');
$this->assertEqual($set[1]['node']->id(), $nodes['promote'][1]->id(), 'Search ranking for promoted second worked.');
@@ -171,14 +172,14 @@ class SearchRankingTest extends SearchTestBase {
// Try with recent, then comments. This is a test for issues
// https://www.drupal.org/node/771596 and
// https://www.drupal.org/node/303574.
$node_ranks = array(
$node_ranks = [
'sticky' => 0,
'promote' => 0,
'relevance' => 0,
'recent' => 10,
'comments' => 1,
'views' => 0,
);
];
$configuration = $this->nodeSearch->getPlugin()->getConfiguration();
foreach ($node_ranks as $var => $value) {
$configuration['rankings'][$var] = $value;
@@ -188,7 +189,7 @@ class SearchRankingTest extends SearchTestBase {
// Do the search and assert the results. The recent node should show up
// first, then the commented node, then all the rest.
$this->nodeSearch->getPlugin()->setSearch('rocks', array(), array());
$this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
$set = $this->nodeSearch->getPlugin()->execute();
$this->assertEqual($set[0]['node']->id(), $nodes['recent'][1]->id(), 'Search ranking for recent first worked.');
$this->assertEqual($set[1]['node']->id(), $nodes['comments'][1]->id(), 'Search ranking for comments second worked.');
@@ -199,33 +200,33 @@ class SearchRankingTest extends SearchTestBase {
* Test rankings of HTML tags.
*/
public function testHTMLRankings() {
$full_html_format = FilterFormat::create(array(
$full_html_format = FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
));
]);
$full_html_format->save();
// Test HTML tags with different weights.
$sorted_tags = array('h1', 'h2', 'h3', 'h4', 'a', 'h5', 'h6', 'notag');
$sorted_tags = ['h1', 'h2', 'h3', 'h4', 'a', 'h5', 'h6', 'notag'];
$shuffled_tags = $sorted_tags;
// Shuffle tags to ensure HTML tags are ranked properly.
shuffle($shuffled_tags);
$settings = array(
$settings = [
'type' => 'page',
'title' => 'Simple node',
);
$nodes = array();
];
$nodes = [];
foreach ($shuffled_tags as $tag) {
switch ($tag) {
case 'a':
$settings['body'] = array(array('value' => \Drupal::l('Drupal Rocks', new Url('<front>')), 'format' => 'full_html'));
$settings['body'] = [['value' => \Drupal::l('Drupal Rocks', new Url('<front>')), 'format' => 'full_html']];
break;
case 'notag':
$settings['body'] = array(array('value' => 'Drupal Rocks'));
$settings['body'] = [['value' => 'Drupal Rocks']];
break;
default:
$settings['body'] = array(array('value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html'));
$settings['body'] = [['value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html']];
break;
}
$nodes[$tag] = $this->drupalCreateNode($settings);
@@ -235,7 +236,7 @@ class SearchRankingTest extends SearchTestBase {
$this->nodeSearch->getPlugin()->updateIndex();
search_update_totals();
$this->nodeSearch->getPlugin()->setSearch('rocks', array(), array());
$this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
// Do the search and assert the results.
$set = $this->nodeSearch->getPlugin()->execute();
@@ -251,16 +252,16 @@ class SearchRankingTest extends SearchTestBase {
}
// Test tags with the same weight against the sorted tags.
$unsorted_tags = array('u', 'b', 'i', 'strong', 'em');
$unsorted_tags = ['u', 'b', 'i', 'strong', 'em'];
foreach ($unsorted_tags as $tag) {
$settings['body'] = array(array('value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html'));
$settings['body'] = [['value' => "<$tag>Drupal Rocks</$tag>", 'format' => 'full_html']];
$node = $this->drupalCreateNode($settings);
// Update the search index.
$this->nodeSearch->getPlugin()->updateIndex();
search_update_totals();
$this->nodeSearch->getPlugin()->setSearch('rocks', array(), array());
$this->nodeSearch->getPlugin()->setSearch('rocks', [], []);
// Do the search and assert the results.
$set = $this->nodeSearch->getPlugin()->execute();
@@ -7,6 +7,9 @@ use Drupal\Component\Utility\SafeMarkup;
/**
* Defines the common search test code.
*
* @deprecated Scheduled for removal in Drupal 9.0.0.
* Use \Drupal\Tests\search\Functional\SearchTestBase instead.
*/
abstract class SearchTestBase extends WebTestBase {
@@ -15,15 +18,15 @@ abstract class SearchTestBase extends WebTestBase {
*
* @var array
*/
public static $modules = array('node', 'search', 'dblog');
public static $modules = ['node', 'search', 'dblog'];
protected function setUp() {
parent::setUp();
// Create Basic page and Article node types.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
}
}
@@ -68,13 +71,13 @@ abstract class SearchTestBase extends WebTestBase {
foreach ($forms as $form) {
// Try to set the fields of this form as specified in $edit.
$edit = $edit_save;
$post = array();
$upload = array();
$post = [];
$upload = [];
$submit_matches = $this->handleForm($post, $edit, $upload, $submit, $form);
if (!$edit && $submit_matches) {
// Everything matched, so "submit" the form.
$action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : NULL;
$this->drupalGet($action, array('query' => $post));
$this->drupalGet($action, ['query' => $post]);
return;
}
}
@@ -82,10 +85,10 @@ abstract class SearchTestBase extends WebTestBase {
// We have not found a form which contained all fields of $edit and
// the submit button.
foreach ($edit as $name => $value) {
$this->fail(SafeMarkup::format('Failed to set field @name to @value', array('@name' => $name, '@value' => $value)));
$this->fail(SafeMarkup::format('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
}
$this->assertTrue($submit_matches, format_string('Found the @submit button', array('@submit' => $submit)));
$this->fail(format_string('Found the requested form fields at @path', array('@path' => $path)));
$this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
$this->fail(format_string('Found the requested form fields at @path', ['@path' => $path]));
}
}
+1 -1
View File
@@ -69,7 +69,7 @@ class ViewsSearchQuery extends SearchQuery {
* item from a \Drupal\Core\Database\Query\Condition::conditions array,
* which must have a 'field' element.
*/
function conditionReplaceString($search, $replace, &$condition) {
public function conditionReplaceString($search, $replace, &$condition) {
if ($condition['field'] instanceof Condition) {
$conditions =& $condition['field']->conditions();
foreach ($conditions as $key => &$subcondition) {