You are here

class UserSearch in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/user/src/Plugin/Search/UserSearch.php \Drupal\user\Plugin\Search\UserSearch

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

Plugin annotation


@SearchPlugin(
  id = "user_search",
  title = @Translation("Users")
)

Hierarchy

Expanded class hierarchy of UserSearch

File

core/modules/user/src/Plugin/Search/UserSearch.php, line 27
Contains \Drupal\user\Plugin\Search\UserSearch.

Namespace

Drupal\user\Plugin\Search
View source
class UserSearch extends SearchPluginBase implements AccessibleInterface {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($container
      ->get('database'), $container
      ->get('entity.manager'), $container
      ->get('module_handler'), $container
      ->get('current_user'), $configuration, $plugin_id, $plugin_definition);
  }

  /**
   * Creates a UserSearch object.
   *
   * @param Connection $database
   *   The database connection.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   */
  public function __construct(Connection $database, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, array $configuration, $plugin_id, $plugin_definition) {
    $this->database = $database;
    $this->entityManager = $entity_manager;
    $this->moduleHandler = $module_handler;
    $this->currentUser = $current_user;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this
      ->addCacheTags([
      'user_list',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    $result = AccessResult::allowedIf(!empty($account) && $account
      ->hasPermission('access user profiles'))
      ->cachePerPermissions();
    return $return_as_object ? $result : $result
      ->isAllowed();
  }

  /**
   * {@inheritdoc}
   */
  public function execute() {
    $results = array();
    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', array(
      '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', array(
        '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->entityManager
      ->getStorage('user')
      ->loadMultiple($uids);
    foreach ($accounts as $account) {
      $result = array(
        'title' => $account
          ->getDisplayName(),
        'link' => $account
          ->url('canonical', array(
          'absolute' => TRUE,
        )),
      );
      if ($this->currentUser
        ->hasPermission('administer users')) {
        $result['title'] .= ' (' . $account
          ->getEmail() . ')';
      }
      $this
        ->addCacheableDependency($account);
      $results[] = $result;
    }
    return $results;
  }

  /*
   * {@inheritdoc}
   */
  public function getHelp() {
    $help = array(
      'list' => array(
        '#theme' => 'item_list',
        '#items' => array(
          $this
            ->t('User search looks for user names and partial user names. Example: mar would match usernames mar, delmar, and maryjane.'),
          $this
            ->t('You can use * as a wildcard within your keyword. Example: m*r would match user names mar, delmar, and elementary.'),
        ),
      ),
    );
    return $help;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
PluginBase::$configuration protected property Configuration information passed into the plugin. 2
PluginBase::$pluginDefinition protected property The plugin implementation definition.
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
RefinableCacheableDependencyTrait::$cacheContexts protected property Cache contexts.
RefinableCacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
RefinableCacheableDependencyTrait::$cacheTags protected property Cache tags.
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::getCacheContexts public function 4
RefinableCacheableDependencyTrait::getCacheMaxAge public function 4
RefinableCacheableDependencyTrait::getCacheTags public function 4
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SearchPluginBase::$keywords protected property The keywords to use in a search.
SearchPluginBase::$searchAttributes protected property Array of attributes - usually from the request object.
SearchPluginBase::$searchParameters protected property Array of parameters from the query string from the request.
SearchPluginBase::buildResults public function Executes the search and builds render arrays for the result items. Overrides SearchInterface::buildResults 1
SearchPluginBase::buildSearchUrlQuery public function Builds the URL GET query parameters array for search. Overrides SearchInterface::buildSearchUrlQuery 1
SearchPluginBase::getAttributes public function Returns the currently set attributes (from the request). Overrides SearchInterface::getAttributes
SearchPluginBase::getKeywords public function Returns the currently set keywords of the plugin instance. Overrides SearchInterface::getKeywords
SearchPluginBase::getParameters public function Returns the current parameters set using setSearch(). Overrides SearchInterface::getParameters
SearchPluginBase::getType public function Returns the search index type this plugin uses. Overrides SearchInterface::getType 1
SearchPluginBase::isSearchExecutable public function Verifies if the values set via setSearch() are valid and sufficient. Overrides SearchInterface::isSearchExecutable 2
SearchPluginBase::searchFormAlter public function Alters the search form when being built for a given plugin. Overrides SearchInterface::searchFormAlter 1
SearchPluginBase::setSearch public function Sets the keywords, parameters, and attributes to be used by execute(). Overrides SearchInterface::setSearch 1
SearchPluginBase::suggestedTitle public function Provides a suggested title for a page of search results. Overrides SearchInterface::suggestedTitle
StringTranslationTrait::$stringTranslation protected property The string translation service.
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UserSearch::$currentUser protected property The current user.
UserSearch::$database protected property The database connection.
UserSearch::$entityManager protected property The entity manager.
UserSearch::$moduleHandler protected property The module handler.
UserSearch::access public function Checks data value access. Overrides AccessibleInterface::access
UserSearch::create public static function Creates an instance of the plugin. Overrides SearchPluginBase::create
UserSearch::execute public function Executes the search. Overrides SearchInterface::execute
UserSearch::getHelp public function Returns the searching help. Overrides SearchPluginBase::getHelp
UserSearch::__construct public function Creates a UserSearch object. Overrides PluginBase::__construct