function UserSearch::execute

Same name in other branches
  1. 8.9.x core/modules/user/src/Plugin/Search/UserSearch.php \Drupal\user\Plugin\Search\UserSearch::execute()
  2. 10 core/modules/user/src/Plugin/Search/UserSearch.php \Drupal\user\Plugin\Search\UserSearch::execute()
  3. 11.x core/modules/user/src/Plugin/Search/UserSearch.php \Drupal\user\Plugin\Search\UserSearch::execute()

Overrides SearchInterface::execute

File

core/modules/user/src/Plugin/Search/UserSearch.php, line 107

Class

UserSearch
Executes a keyword search for users against the {users} database table.

Namespace

Drupal\user\Plugin\Search

Code

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(PagerSelectExtender::class);
    $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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.