public function UserSearch::execute in Drupal 8
Same name and namespace in other branches
- 9 core/modules/user/src/Plugin/Search/UserSearch.php \Drupal\user\Plugin\Search\UserSearch::execute()
Executes the search.
Return value
array A structured list of search results.
Overrides SearchInterface::execute
File
- core/
modules/ user/ src/ Plugin/ Search/ UserSearch.php, line 113
Class
- UserSearch
- Executes a keyword search for users against the {users} database table.
Namespace
Drupal\user\Plugin\SearchCode
public function execute() {
$results = [];
if (!$this
->isSearchExecutable()) {
return $results;
}
// Process the keywords.
$keys = $this->keywords;
// Escape for LIKE matching.
$keys = $this->database
->escapeLike($keys);
// Replace wildcards with MySQL/PostgreSQL wildcards.
$keys = preg_replace('!\\*+!', '%', $keys);
// Run the query to find matching users.
$query = $this->database
->select('users_field_data', 'users')
->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender');
$query
->fields('users', [
'uid',
]);
$query
->condition('default_langcode', 1);
if ($this->currentUser
->hasPermission('administer users')) {
// Administrators can also search in the otherwise private email field,
// and they don't need to be restricted to only active users.
$query
->fields('users', [
'mail',
]);
$query
->condition($query
->orConditionGroup()
->condition('name', '%' . $keys . '%', 'LIKE')
->condition('mail', '%' . $keys . '%', 'LIKE'));
}
else {
// Regular users can only search via usernames, and we do not show them
// blocked accounts.
$query
->condition('name', '%' . $keys . '%', 'LIKE')
->condition('status', 1);
}
$uids = $query
->limit(15)
->execute()
->fetchCol();
$accounts = $this->entityTypeManager
->getStorage('user')
->loadMultiple($uids);
foreach ($accounts as $account) {
$result = [
'title' => $account
->getDisplayName(),
'link' => $account
->toUrl('canonical', [
'absolute' => TRUE,
])
->toString(),
];
if ($this->currentUser
->hasPermission('administer users')) {
$result['title'] .= ' (' . $account
->getEmail() . ')';
}
$this
->addCacheableDependency($account);
$results[] = $result;
}
return $results;
}