You are here

class UserPermissionsForm in User Permissions 8

User permissions form for granting permissions to individual users.

Hierarchy

Expanded class hierarchy of UserPermissionsForm

1 string reference to 'UserPermissionsForm'
user_permissions.routing.yml in ./user_permissions.routing.yml
user_permissions.routing.yml

File

src/Form/UserPermissionsForm.php, line 20

Namespace

Drupal\user_permissions\Form
View source
class UserPermissionsForm extends UserPermissionsRoleSpecificForm {

  /**
   * Current user from current session.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * Current user.
   *
   * @var \Drupal\user\Entity\User
   */
  protected $user;

  /**
   * Constructs a new UserPermissionsForm.
   *
   * @param \Drupal\user\PermissionHandlerInterface $permission_handler
   *   The permission handler.
   * @param \Drupal\user\RoleStorageInterface $role_storage
   *   The role storage.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The user from current session.
   */
  public function __construct(PermissionHandlerInterface $permission_handler, RoleStorageInterface $role_storage, ModuleHandlerInterface $module_handler, AccountInterface $account) {
    parent::__construct($permission_handler, $role_storage, $module_handler);
    $this->account = $account;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('user.permissions'), $container
      ->get('entity.manager')
      ->getStorage('user_role'), $container
      ->get('module_handler'), $container
      ->get('current_user'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $user = NULL) {
    if (!$this->account
      ->hasPermission('administer permissions')) {
      return new RedirectResponse(Url::fromRoute('user.page'));
    }
    if (!is_null($user)) {
      $uid = $user;
      $this->user = User::load($uid);
    }
    else {
      $form['user'] = [
        '#markup' => $this
          ->t('User could not be found.'),
      ];
      return $form;
    }

    // Set user specific role name.
    $role_name = '_user_role_' . $uid;

    // Check for the existence of this role.
    $role = Role::load($role_name);
    if ($role) {

      // If role exists, use this for the UserPermissionsRoleSpecificForm.
      $this->userRole = Role::load($role_name);
      $form = parent::buildForm($form, $form_state, $this->userRole);
    }
    else {

      // If role does not exists,
      // load the dummy role and use it to define base permissions.
      $this->userRole = Role::load(USER_PERMISSIONS_NO_ROLE);
      $form = parent::buildForm($form, $form_state, $this->userRole);
      foreach ($form['permissions']['#header'] as $key => &$data) {
        if (is_array($data) && array_key_exists('data', $data)) {
          $data['data'] = $role_name;
        }
      }
      $form['permissions'][$this->userRole
        ->id()]['#default_value'] = [];
      $form['role_names']['#value'][$this->userRole
        ->id()] = $role_name;
    }

    // Check for blocked permissions.
    $blocked_permissions = [];
    $user_roles = $this->user
      ->getRoles();
    foreach (user_role_permissions($user_roles) as $rid => $permissions) {
      if ($rid != $role
        ->get('id')) {
        $blocked_permissions += array_filter($permissions);
      }
    }
    $rid = $role
      ->get('id');
    foreach ($blocked_permissions as $permission) {
      if (isset($form['permissions'][$permission][$rid])) {
        $form['permissions'][$permission][$rid]['#default_value'] = 1;
        $form['permissions'][$permission][$rid]['#value'] = $permission;
        $form['permissions'][$permission][$rid]['#disabled'] = TRUE;
        $form['permissions'][$permission][$rid]['#attributes']['checked'] = TRUE;
      }
    }
    $form['role_names'][$this->userRole
      ->id()]['#markup'] = 'Enable?';
    $form['role_name'] = [
      '#type' => 'hidden',
      '#value' => $this->userRole
        ->label(),
    ];
    $form['uid'] = [
      '#type' => 'hidden',
      '#value' => $uid,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $perms = [];
    $uid = (int) $form_state
      ->getValue('uid');
    $role_name = $form_state
      ->getValue('role_name');
    $input = $form_state
      ->getUserInput();
    if (array_key_exists($role_name, $input)) {
      $perms = $input[$role_name];
    }
    if ($role_name == USER_PERMISSIONS_NO_ROLE) {
      if (!empty($perms)) {

        // Creates a new role with the name $role_name.
        $role_name = '_user_role_' . $uid;
        $this->userRole = Role::create([
          'id' => $role_name,
          'label' => $role_name,
        ]);
        $this->userRole
          ->save();
        foreach ($form_state
          ->getValue('role_names') as $role_name => $name) {
          user_role_change_permissions($this->userRole
            ->label(), (array) $form_state
            ->getValue($role_name));
        }
      }

      // If $perms contains no permissions for the user, no role is created.
    }
    else {

      // Modifying existing user permissions.
      $perms_exist = array_filter($perms);
      if (empty($perms_exist)) {

        // If $perms has no permissions for the user,
        // this deletes all permission/role information related to this role.
        $this->userRole
          ->delete();
      }
      else {
        foreach ($form_state
          ->getValue('role_names') as $role_name => $name) {
          user_role_change_permissions($role_name, (array) $form_state
            ->getValue($role_name));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_permissions_form';
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.
UserPermissionsForm::$account protected property Current user from current session.
UserPermissionsForm::$moduleHandler protected property The module handler.
UserPermissionsForm::$permissionHandler protected property The permission handler.
UserPermissionsForm::$roleStorage protected property The role storage.
UserPermissionsForm::$user protected property Current user.
UserPermissionsForm::buildForm public function Builds the user permissions administration form for a specific role. Overrides UserPermissionsRoleSpecificForm::buildForm
UserPermissionsForm::create public static function Instantiates a new instance of this class. Overrides UserPermissionsForm::create
UserPermissionsForm::getFormId public function Returns a unique string identifying the form. Overrides UserPermissionsForm::getFormId
UserPermissionsForm::submitForm public function Form submission handler. Overrides UserPermissionsForm::submitForm
UserPermissionsForm::__construct public function Constructs a new UserPermissionsForm. Overrides UserPermissionsForm::__construct
UserPermissionsRoleSpecificForm::$userRole protected property The specific role for this form.
UserPermissionsRoleSpecificForm::getRoles protected function Gets the roles to display in this form. Overrides UserPermissionsForm::getRoles