class SwitchUserBlock in Devel 8.3
Same name and namespace in other branches
- 8 src/Plugin/Block/SwitchUserBlock.php \Drupal\devel\Plugin\Block\SwitchUserBlock
- 8.2 src/Plugin/Block/SwitchUserBlock.php \Drupal\devel\Plugin\Block\SwitchUserBlock
- 4.x src/Plugin/Block/SwitchUserBlock.php \Drupal\devel\Plugin\Block\SwitchUserBlock
Provides a block for switching users.
Plugin annotation
@Block(
  id = "devel_switch_user",
  admin_label = @Translation("Switch user"),
  category = "Devel"
)
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface- class \Drupal\Component\Plugin\ContextAwarePluginBase implements ContextAwarePluginInterface- class \Drupal\Core\Plugin\ContextAwarePluginBase implements CacheableDependencyInterface, ContextAwarePluginInterface uses DependencySerializationTrait, StringTranslationTrait, TypedDataTrait- class \Drupal\Core\Block\BlockBase implements BlockPluginInterface, PluginWithFormsInterface, PreviewFallbackInterface uses BlockPluginTrait, ContextAwarePluginAssignmentTrait- class \Drupal\devel\Plugin\Block\SwitchUserBlock implements ContainerFactoryPluginInterface uses RedirectDestinationTrait
 
 
- class \Drupal\Core\Block\BlockBase implements BlockPluginInterface, PluginWithFormsInterface, PreviewFallbackInterface uses BlockPluginTrait, ContextAwarePluginAssignmentTrait
 
- class \Drupal\Core\Plugin\ContextAwarePluginBase implements CacheableDependencyInterface, ContextAwarePluginInterface uses DependencySerializationTrait, StringTranslationTrait, TypedDataTrait
 
- class \Drupal\Component\Plugin\ContextAwarePluginBase implements ContextAwarePluginInterface
Expanded class hierarchy of SwitchUserBlock
File
- src/Plugin/ Block/ SwitchUserBlock.php, line 28 
Namespace
Drupal\devel\Plugin\BlockView source
class SwitchUserBlock extends BlockBase implements ContainerFactoryPluginInterface {
  use RedirectDestinationTrait;
  /**
   * The FormBuilder object.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;
  /**
   * The Current User object.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;
  /**
   * The user storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;
  /**
   * Constructs a new SwitchUserBlock object.
   *
   * @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.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   Current user.
   * @param \Drupal\Core\Entity\EntityStorageInterface $user_storage
   *   The user storage.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountInterface $current_user, EntityStorageInterface $user_storage, FormBuilderInterface $form_builder) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->formBuilder = $form_builder;
    $this->currentUser = $current_user;
    $this->userStorage = $user_storage;
  }
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('current_user'), $container
      ->get('entity_type.manager')
      ->getStorage('user'), $container
      ->get('form_builder'));
  }
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'list_size' => 12,
      'include_anon' => FALSE,
      'show_form' => TRUE,
    ];
  }
  /**
   * {@inheritdoc}
   */
  public function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'switch users');
  }
  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $anonymous = new AnonymousUserSession();
    $form['list_size'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Number of users to display in the list'),
      '#default_value' => $this->configuration['list_size'],
      '#min' => 1,
      '#max' => 50,
    ];
    $form['include_anon'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Include %anonymous', [
        '%anonymous' => $anonymous
          ->getDisplayName(),
      ]),
      '#default_value' => $this->configuration['include_anon'],
    ];
    $form['show_form'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Allow entering any user name'),
      '#default_value' => $this->configuration['show_form'],
    ];
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['list_size'] = $form_state
      ->getValue('list_size');
    $this->configuration['include_anon'] = $form_state
      ->getValue('include_anon');
    $this->configuration['show_form'] = $form_state
      ->getValue('show_form');
  }
  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return 0;
  }
  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    if ($accounts = $this
      ->getUsers()) {
      $build['devel_links'] = $this
        ->buildUserList($accounts);
      if ($this->configuration['show_form']) {
        $build['devel_form'] = $this->formBuilder
          ->getForm('\\Drupal\\devel\\Form\\SwitchUserForm');
      }
    }
    return $build;
  }
  /**
   * Provides the list of accounts that can be used for the user switch.
   *
   * Inactive users are omitted from all of the following db selects. Users
   * with 'switch users' permission and anonymous user if include_anon property
   * is set to TRUE, are prioritized.
   *
   * @return \Drupal\Core\Session\AccountInterface[]
   *   List of accounts to be used for the switch.
   */
  protected function getUsers() {
    $list_size = $this->configuration['list_size'];
    $include_anonymous = $this->configuration['include_anon'];
    $list_size = $include_anonymous ? $list_size - 1 : $list_size;
    // Users with 'switch users' permission are prioritized so
    // we try to load first users with this permission.
    $query = $this->userStorage
      ->getQuery()
      ->condition('uid', 0, '>')
      ->condition('status', 0, '>')
      ->sort('access', 'DESC')
      ->range(0, $list_size);
    $roles = user_roles(TRUE, 'switch users');
    if (!empty($roles) && !isset($roles[Role::AUTHENTICATED_ID])) {
      $query
        ->condition('roles', array_keys($roles), 'IN');
    }
    $user_ids = $query
      ->execute();
    // If we don't have enough users with 'switch users' permission, add
    // uids until we hit $list_size.
    if (count($user_ids) < $list_size) {
      $query = $this->userStorage
        ->getQuery()
        ->condition('uid', 0, '>')
        ->condition('status', 0, '>')
        ->sort('access', 'DESC')
        ->range(0, $list_size);
      // Excludes the prioritized user ids only if the previous query return
      // some records.
      if (!empty($user_ids)) {
        $query
          ->condition('uid', array_keys($user_ids), 'NOT IN');
        $query
          ->range(0, $list_size - count($user_ids));
      }
      $user_ids += $query
        ->execute();
    }
    /** @var \Drupal\Core\Session\AccountInterface[] $accounts */
    $accounts = $this->userStorage
      ->loadMultiple($user_ids);
    if ($include_anonymous) {
      $anonymous = new AnonymousUserSession();
      $accounts[$anonymous
        ->id()] = $anonymous;
    }
    uasort($accounts, 'static::sortUserList');
    return $accounts;
  }
  /**
   * Builds the user listing as renderable array.
   *
   * @param \Drupal\core\Session\AccountInterface[] $accounts
   *   The accounts to be rendered in the list.
   *
   * @return array
   *   A renderable array.
   */
  protected function buildUserList(array $accounts) {
    $links = [];
    foreach ($accounts as $account) {
      $links[$account
        ->id()] = [
        'title' => $account
          ->getDisplayName(),
        'url' => Url::fromRoute('devel.switch', [
          'name' => $account
            ->getAccountName(),
        ]),
        'query' => $this
          ->getDestinationArray(),
        'attributes' => [
          'title' => $account
            ->hasPermission('switch users') ? $this
            ->t('This user can switch back.') : $this
            ->t('Caution: this user will be unable to switch back.'),
        ],
      ];
      if ($account
        ->isAnonymous()) {
        $links[$account
          ->id()]['url'] = Url::fromRoute('user.logout');
      }
      if ($this->currentUser
        ->id() === $account
        ->id()) {
        $links[$account
          ->id()]['title'] = new FormattableMarkup('<strong>%user</strong>', [
          '%user' => $account
            ->getDisplayName(),
        ]);
      }
    }
    return [
      '#theme' => 'links',
      '#links' => $links,
      '#attached' => [
        'library' => [
          'devel/devel',
        ],
      ],
    ];
  }
  /**
   * Helper callback for uasort() to sort accounts by last access.
   *
   * @param \Drupal\Core\Session\AccountInterface $a
   *   First account.
   * @param \Drupal\Core\Session\AccountInterface $b
   *   Second account.
   *
   * @return int
   *   Result of comparing the last access times:
   *   - -1 if $a was more recently accessed
   *   -  0 if last access times compare equal
   *   -  1 if $b was more recently accessed
   */
  public static function sortUserList(AccountInterface $a, AccountInterface $b) {
    $a_access = (int) $a
      ->getLastAccessedTime();
    $b_access = (int) $b
      ->getLastAccessedTime();
    if ($a_access === $b_access) {
      return 0;
    }
    // User never access to site.
    if ($a_access === 0) {
      return 1;
    }
    return $a_access > $b_access ? -1 : 1;
  }
}Members
| Name   | Modifiers | Type | Description | Overrides | 
|---|---|---|---|---|
| BlockPluginInterface:: | constant | Indicates the block label (title) should be displayed to end users. | ||
| BlockPluginTrait:: | protected | property | The transliteration service. | |
| BlockPluginTrait:: | public | function | ||
| BlockPluginTrait:: | protected | function | Returns generic default configuration for block plugins. | |
| BlockPluginTrait:: | public | function | 3 | |
| BlockPluginTrait:: | public | function | Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. | 2 | 
| BlockPluginTrait:: | public | function | ||
| BlockPluginTrait:: | public | function | 1 | |
| BlockPluginTrait:: | public | function | 1 | |
| BlockPluginTrait:: | public | function | 3 | |
| BlockPluginTrait:: | public | function | ||
| BlockPluginTrait:: | public | function | ||
| BlockPluginTrait:: | public | function | ||
| BlockPluginTrait:: | public | function | Sets the transliteration service. | |
| BlockPluginTrait:: | public | function | Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit(). | |
| BlockPluginTrait:: | protected | function | Wraps the transliteration service. | |
| BlockPluginTrait:: | public | function | Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). | 1 | 
| ContextAwarePluginAssignmentTrait:: | protected | function | Builds a form element for assigning a context to a given slot. | |
| ContextAwarePluginAssignmentTrait:: | protected | function | Wraps the context handler. | |
| ContextAwarePluginBase:: | protected | property | The data objects representing the context of this plugin. | |
| ContextAwarePluginBase:: | private | property | Data objects representing the contexts passed in the plugin configuration. | |
| ContextAwarePluginBase:: | protected | function | Overrides ContextAwarePluginBase:: | |
| ContextAwarePluginBase:: | public | function | The cache contexts associated with this object. Overrides CacheableDependencyInterface:: | 9 | 
| ContextAwarePluginBase:: | public | function | The cache tags associated with this object. Overrides CacheableDependencyInterface:: | 4 | 
| ContextAwarePluginBase:: | public | function | This code is identical to the Component in order to pick up a different
Context class. Overrides ContextAwarePluginBase:: | |
| ContextAwarePluginBase:: | public | function | Overrides ContextAwarePluginBase:: | |
| ContextAwarePluginBase:: | public | function | Overrides ContextAwarePluginBase:: | |
| ContextAwarePluginBase:: | public | function | Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface:: | |
| ContextAwarePluginBase:: | public | function | Gets the defined contexts. Overrides ContextAwarePluginInterface:: | |
| ContextAwarePluginBase:: | public | function | Gets the value for a defined context. Overrides ContextAwarePluginInterface:: | |
| ContextAwarePluginBase:: | public | function | Gets the values for all defined contexts. Overrides ContextAwarePluginInterface:: | |
| ContextAwarePluginBase:: | public | function | Set a context on this plugin. Overrides ContextAwarePluginBase:: | |
| ContextAwarePluginBase:: | public | function | Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface:: | |
| ContextAwarePluginBase:: | public | function | Sets the value for a defined context. Overrides ContextAwarePluginBase:: | |
| ContextAwarePluginBase:: | public | function | Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface:: | |
| ContextAwarePluginBase:: | public | function | Implements magic __get() method. | |
| DependencySerializationTrait:: | protected | property | An array of entity type IDs keyed by the property name of their storages. | |
| DependencySerializationTrait:: | protected | property | An array of service IDs keyed by property name used for serialization. | |
| DependencySerializationTrait:: | public | function | 1 | |
| DependencySerializationTrait:: | public | function | 2 | |
| MessengerTrait:: | protected | property | The messenger. | 29 | 
| MessengerTrait:: | public | function | Gets the messenger. | 29 | 
| MessengerTrait:: | public | function | Sets the messenger. | |
| PluginBase:: | protected | property | Configuration information passed into the plugin. | 1 | 
| PluginBase:: | protected | property | The plugin implementation definition. | 1 | 
| PluginBase:: | protected | property | The plugin_id. | |
| PluginBase:: | constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
| PluginBase:: | public | function | Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: | |
| PluginBase:: | public | function | Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: | |
| PluginBase:: | public | function | Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: | 3 | 
| PluginBase:: | public | function | Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: | |
| PluginBase:: | public | function | Determines if the plugin is configurable. | |
| PluginWithFormsTrait:: | public | function | ||
| PluginWithFormsTrait:: | public | function | ||
| RedirectDestinationTrait:: | protected | property | The redirect destination service. | 1 | 
| RedirectDestinationTrait:: | protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
| RedirectDestinationTrait:: | protected | function | Returns the redirect destination service. | |
| RedirectDestinationTrait:: | public | function | Sets the redirect destination service. | |
| StringTranslationTrait:: | protected | property | The string translation service. | 1 | 
| StringTranslationTrait:: | protected | function | Formats a string containing a count of items. | |
| StringTranslationTrait:: | protected | function | Returns the number of plurals supported by a given language. | |
| StringTranslationTrait:: | protected | function | Gets the string translation service. | |
| StringTranslationTrait:: | public | function | Sets the string translation service to use. | 2 | 
| StringTranslationTrait:: | protected | function | Translates a string to the current language or to a given language. | |
| SwitchUserBlock:: | protected | property | The Current User object. | |
| SwitchUserBlock:: | protected | property | The FormBuilder object. | |
| SwitchUserBlock:: | protected | property | The user storage. | |
| SwitchUserBlock:: | public | function | Indicates whether the block should be shown. Overrides BlockPluginTrait:: | |
| SwitchUserBlock:: | public | function | Overrides BlockPluginTrait:: | |
| SwitchUserBlock:: | public | function | Overrides BlockPluginTrait:: | |
| SwitchUserBlock:: | public | function | Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface:: | |
| SwitchUserBlock:: | protected | function | Builds the user listing as renderable array. | |
| SwitchUserBlock:: | public static | function | Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface:: | |
| SwitchUserBlock:: | public | function | Overrides BlockPluginTrait:: | |
| SwitchUserBlock:: | public | function | The maximum age for which this object may be cached. Overrides ContextAwarePluginBase:: | |
| SwitchUserBlock:: | protected | function | Provides the list of accounts that can be used for the user switch. | |
| SwitchUserBlock:: | public static | function | Helper callback for uasort() to sort accounts by last access. | |
| SwitchUserBlock:: | public | function | Constructs a new SwitchUserBlock object. Overrides BlockPluginTrait:: | |
| TypedDataTrait:: | protected | property | The typed data manager used for creating the data types. | |
| TypedDataTrait:: | public | function | Gets the typed data manager. | 2 | 
| TypedDataTrait:: | public | function | Sets the typed data manager. | 2 | 
