class UserSession
An implementation of the user account interface for the global user.
Attributes
#[\AllowDynamicProperties]
  Hierarchy
- class \Drupal\Core\Session\UserSession implements \Drupal\Core\Session\AccountInterface
 
Expanded class hierarchy of UserSession
11 files declare their use of UserSession
- AccountProxyTest.php in core/
tests/ Drupal/ Tests/ Core/ Session/ AccountProxyTest.php  - AccountSwitcherTest.php in core/
tests/ Drupal/ KernelTests/ Core/ Session/ AccountSwitcherTest.php  - ContentModerationAccessTest.php in core/
modules/ content_moderation/ tests/ src/ Kernel/ ContentModerationAccessTest.php  - Cookie.php in core/
modules/ user/ src/ Authentication/ Provider/ Cookie.php  - FormCacheTest.php in core/
tests/ Drupal/ KernelTests/ Core/ Form/ FormCacheTest.php  
File
- 
              core/
lib/ Drupal/ Core/ Session/ UserSession.php, line 8  
Namespace
Drupal\Core\SessionView source
class UserSession implements AccountInterface {
  
  /**
   * User ID.
   *
   * @var int
   */
  protected $uid = 0;
  
  /**
   * List of the roles this user has.
   *
   * Defaults to the anonymous role.
   *
   * @var array
   */
  protected $roles = [
    AccountInterface::ANONYMOUS_ROLE,
  ];
  
  /**
   * The Unix timestamp when the user last accessed the site.
   *
   * @var string
   */
  protected $access;
  
  /**
   * The name of this account.
   *
   * @var string
   */
  protected $name = '';
  
  /**
   * The preferred language code of the account.
   *
   * @var string
   */
  // phpcs:ignore Drupal.NamingConventions.ValidVariableName.LowerCamelName, Drupal.Commenting.VariableComment.Missing
  protected $preferred_langcode;
  
  /**
   * The preferred administrative language code of the account.
   *
   * @var string
   */
  // phpcs:ignore Drupal.NamingConventions.ValidVariableName.LowerCamelName, Drupal.Commenting.VariableComment.Missing
  protected $preferred_admin_langcode;
  
  /**
   * The email address of this account.
   *
   * @var string
   */
  protected $mail;
  
  /**
   * The timezone of this account.
   *
   * @var string
   */
  protected $timezone;
  
  /**
   * Constructs a new user session.
   *
   * @param array $values
   *   Array of initial values for the user session.
   */
  public function __construct(array $values = []) {
    foreach ($values as $key => $value) {
      $this->{$key} = $value;
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function id() {
    return $this->uid;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getRoles($exclude_locked_roles = FALSE) {
    $roles = $this->roles;
    if ($exclude_locked_roles) {
      $roles = array_values(array_diff($roles, [
        AccountInterface::ANONYMOUS_ROLE,
        AccountInterface::AUTHENTICATED_ROLE,
      ]));
    }
    return $roles;
  }
  
  /**
   * Whether a user has a certain role.
   *
   * @param string $rid
   *   The role ID to check.
   *
   * @return bool
   *   Returns TRUE if the user has the role, otherwise FALSE.
   *
   * @todo in Drupal 11, add method to Drupal\Core\Session\AccountInterface.
   * @see https://www.drupal.org/node/3228209
   */
  public function hasRole(string $rid) : bool {
    return in_array($rid, $this->getRoles(), TRUE);
  }
  
  /**
   * {@inheritdoc}
   */
  public function hasPermission(string $permission) {
    return \Drupal::service('permission_checker')->hasPermission($permission, $this);
  }
  
  /**
   * {@inheritdoc}
   */
  public function isAuthenticated() {
    return $this->uid > 0;
  }
  
  /**
   * {@inheritdoc}
   */
  public function isAnonymous() {
    return $this->uid == 0;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getPreferredLangcode($fallback_to_default = TRUE) {
    $language_list = \Drupal::languageManager()->getLanguages();
    if (!empty($this->preferred_langcode) && isset($language_list[$this->preferred_langcode])) {
      return $language_list[$this->preferred_langcode]
        ->getId();
    }
    else {
      return $fallback_to_default ? \Drupal::languageManager()->getDefaultLanguage()
        ->getId() : '';
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function getPreferredAdminLangcode($fallback_to_default = TRUE) {
    $language_list = \Drupal::languageManager()->getLanguages();
    if (!empty($this->preferred_admin_langcode) && isset($language_list[$this->preferred_admin_langcode])) {
      return $language_list[$this->preferred_admin_langcode]
        ->getId();
    }
    else {
      return $fallback_to_default ? \Drupal::languageManager()->getDefaultLanguage()
        ->getId() : '';
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function getAccountName() {
    return $this->name;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getDisplayName() {
    $name = $this->name ?: \Drupal::config('user.settings')->get('anonymous');
    \Drupal::moduleHandler()->alter('user_format_name', $name, $this);
    return $name;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getEmail() {
    return $this->mail;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getTimeZone() {
    return $this->timezone;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getLastAccessedTime() {
    return $this->access;
  }
  
  /**
   * Returns the role storage object.
   *
   * @return \Drupal\user\RoleStorageInterface
   *   The role storage object.
   */
  protected function getRoleStorage() {
    return \Drupal::entityTypeManager()->getStorage('user_role');
  }
  
  /**
   * Implements magic __get() method.
   */
  public function __get($name) : mixed {
    if ($name === 'name') {
      @trigger_error("Getting the name property is deprecated in drupal:11.3.0 and is removed from drupal:12.0.0. Use \\Drupal\\Core\\Session\\UserSession::getAccountName() instead. See https://www.drupal.org/node/3513856", E_USER_DEPRECATED);
      return $this->getAccountName();
    }
    $class = get_class($this);
    $properties = get_class_vars($class);
    if (\array_key_exists($name, $properties)) {
      throw new \LogicException("Cannot access protected property {$name} in " . $class);
    }
    return $this->{$name} ?? NULL;
  }
  
  /**
   * Implements magic __isset() method.
   */
  public function __isset($name) : bool {
    if ($name === 'name') {
      @trigger_error("Checking for the name property is deprecated in drupal:11.3.0 and is removed from drupal:12.0.0. Use \\Drupal\\Core\\Session\\UserSession::getAccountName() instead. See https://www.drupal.org/node/3513856", E_USER_DEPRECATED);
      return isset($this->name);
    }
    $class = get_class($this);
    $properties = get_class_vars($class);
    if (\array_key_exists($name, $properties)) {
      throw new \LogicException("Cannot access protected property {$name} in " . $class);
    }
    return isset($this->{$name});
  }
  
  /**
   * Implements magic __set() method.
   */
  public function __set($name, $value) : void {
    if ($name === 'name') {
      @trigger_error("Setting the name property is deprecated in drupal:11.3.0 and is removed from drupal:12.0.0. Set the name via the constructor when creating the UserSession instance. See https://www.drupal.org/node/3513856", E_USER_DEPRECATED);
      $this->name = $value;
      return;
    }
    $class = get_class($this);
    $properties = get_class_vars($class);
    if (\array_key_exists($name, $properties)) {
      throw new \LogicException("Cannot set protected property {$name} in " . $class);
    }
    $this->{$name} = $value;
  }
}
Members
| Title Sort descending | Modifiers | Object type | Summary | Overriden Title | Overrides | 
|---|---|---|---|---|---|
| AccountInterface::ANONYMOUS_ROLE | constant | Role ID for anonymous users. | |||
| AccountInterface::AUTHENTICATED_ROLE | constant | Role ID for authenticated users. | |||
| UserSession::$access | protected | property | The Unix timestamp when the user last accessed the site. | ||
| UserSession::$mail | protected | property | The email address of this account. | ||
| UserSession::$name | protected | property | The name of this account. | ||
| UserSession::$preferred_admin_langcode | protected | property | The preferred administrative language code of the account. | ||
| UserSession::$preferred_langcode | protected | property | The preferred language code of the account. | ||
| UserSession::$roles | protected | property | List of the roles this user has. | ||
| UserSession::$timezone | protected | property | The timezone of this account. | ||
| UserSession::$uid | protected | property | User ID. | ||
| UserSession::getAccountName | public | function | Returns the unaltered login name of this account. | Overrides AccountInterface::getAccountName | |
| UserSession::getDisplayName | public | function | Returns the display name of this account. | Overrides AccountInterface::getDisplayName | |
| UserSession::getEmail | public | function | Returns the email address of this account. | Overrides AccountInterface::getEmail | |
| UserSession::getLastAccessedTime | public | function | The timestamp when the account last accessed the site. | Overrides AccountInterface::getLastAccessedTime | |
| UserSession::getPreferredAdminLangcode | public | function | Returns the preferred administrative language code of the account. | Overrides AccountInterface::getPreferredAdminLangcode | |
| UserSession::getPreferredLangcode | public | function | Returns the preferred language code of the account. | Overrides AccountInterface::getPreferredLangcode | |
| UserSession::getRoles | public | function | Returns a list of roles. | Overrides AccountInterface::getRoles | |
| UserSession::getRoleStorage | protected | function | Returns the role storage object. | ||
| UserSession::getTimeZone | public | function | Returns the timezone of this account. | Overrides AccountInterface::getTimeZone | |
| UserSession::hasPermission | public | function | Checks whether a user has a certain permission. | Overrides AccountInterface::hasPermission | |
| UserSession::hasRole | public | function | Whether a user has a certain role. | ||
| UserSession::id | public | function | Returns the user ID or 0 for anonymous. | Overrides AccountInterface::id | |
| UserSession::isAnonymous | public | function | Returns TRUE if the account is anonymous. | Overrides AccountInterface::isAnonymous | |
| UserSession::isAuthenticated | public | function | Returns TRUE if the account is authenticated. | Overrides AccountInterface::isAuthenticated | |
| UserSession::__construct | public | function | Constructs a new user session. | 1 | |
| UserSession::__get | public | function | Implements magic __get() method. | ||
| UserSession::__isset | public | function | Implements magic __isset() method. | ||
| UserSession::__set | public | function | Implements magic __set() method. | 
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.