You are here

class AssignUserForm in Workbench Access 8

Builds the workbench_access set switch form.

@internal

Hierarchy

Expanded class hierarchy of AssignUserForm

1 string reference to 'AssignUserForm'
workbench_access.routing.yml in ./workbench_access.routing.yml
workbench_access.routing.yml

File

src/Form/AssignUserForm.php, line 24

Namespace

Drupal\workbench_access\Form
View source
class AssignUserForm extends FormBase {

  /**
   * The user account being edited.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * Workbnech Access manager.
   *
   * @var \Drupal\workbench_access\WorkbenchAccessManagerInterface
   */
  protected $manager;

  /**
   * The access scheme storage handler.
   *
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
   */
  protected $schemeStorage;

  /**
   * The section storage handler.
   *
   * @var \Drupal\workbench_access\SectionAssociationStorageInterface
   */
  protected $sectionStorage;

  /**
   * The user section storage service.
   *
   * @var \Drupal\workbench_access\UserSectionStorageInterface
   */
  protected $userSectionStorage;

  /**
   * The role section storage service.
   *
   * @var \Drupal\workbench_access\RoleSectionStorageInterface
   */
  protected $roleSectionStorage;

  /**
   * Constructs the form object.
   *
   * @param \Drupal\workbench_access\WorkbenchAccessManagerInterface $manager
   *   The workbench access manager.
   * @param \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $scheme_storage
   *   The access scheme storage handler.
   * @param \Drupal\workbench_access\SectionAssociationStorageInterface $section_storage
   *   The section storage handler.
   * @param \Drupal\workbench_access\UserSectionStorageInterface $user_section_storage
   *   The user section storage service.
   * @param \Drupal\workbench_access\RoleSectionStorageInterface $role_section_storage
   *   The role section storage service.
   */
  public function __construct(WorkbenchAccessManagerInterface $manager, ConfigEntityStorageInterface $scheme_storage, SectionAssociationStorageInterface $section_storage, UserSectionStorageInterface $user_section_storage, RoleSectionStorageInterface $role_section_storage) {
    $this->manager = $manager;
    $this->schemeStorage = $scheme_storage;
    $this->sectionStorage = $section_storage;
    $this->userSectionStorage = $user_section_storage;
    $this->roleSectionStorage = $role_section_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.workbench_access.scheme'), $container
      ->get('entity_type.manager')
      ->getStorage('access_scheme'), $container
      ->get('entity_type.manager')
      ->getStorage('section_association'), $container
      ->get('workbench_access.user_section_storage'), $container
      ->get('workbench_access.role_section_storage'));
  }

  /**
   * Checks access to the form from the route.
   *
   * This form is only visible on accounts that can use Workbench Access,
   * regardless of the current user's permissions.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The account accessing the form.
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The user being edited.
   */
  public function access(AccountInterface $account, AccountInterface $user) {
    return AccessResult::allowedIf($user
      ->hasPermission('use workbench access'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) {
    $account = $this
      ->currentUser();
    $this->user = $user;
    $form_enabled = FALSE;
    $active_schemes = [];

    // Load all schemes.
    $schemes = $this->schemeStorage
      ->loadMultiple();
    foreach ($schemes as $scheme) {
      $user_sections = $this->userSectionStorage
        ->getUserSections($scheme, $user, FALSE);
      $options = $this
        ->getFormOptions($scheme);
      $role_sections = $this->roleSectionStorage
        ->getRoleSections($scheme, $user);
      $list = array_flip($role_sections);
      foreach ($options as $value => $label) {
        if (isset($list[$value])) {
          $options[$value] = '<strong>' . $label . ' * </strong>';
        }
      }
      if (!empty($options)) {
        $form[$scheme
          ->id()] = [
          '#type' => 'fieldset',
          '#collapsible' => TRUE,
          '#collapsed' => FALSE,
          '#title' => $scheme
            ->getPluralLabel(),
        ];
        $form[$scheme
          ->id()]['active_' . $scheme
          ->id()] = [
          '#type' => 'checkboxes',
          '#title' => $this
            ->t('Assigned sections'),
          '#options' => $options,
          '#default_value' => $user_sections,
          '#description' => $this
            ->t('Sections assigned by role are <strong>emphasized</strong> and marked with an * but not selected unless they are also assigned directly to the user. They need not be selected. Access granted by role cannot be revoked from this form.'),
        ];
        $form[$scheme
          ->id()]['scheme_' . $scheme
          ->id()] = [
          '#type' => 'value',
          '#value' => $scheme,
        ];
        $form_enabled = TRUE;
        $active_schemes[] = $scheme
          ->id();
      }
    }
    if ($form_enabled) {
      $form['schemes'] = [
        '#type' => 'value',
        '#value' => $active_schemes,
      ];
      $form['actions'] = [
        '#type' => 'actions',
        'submit' => [
          '#type' => 'submit',
          '#name' => 'save',
          '#value' => $this
            ->t('Save'),
        ],
      ];
    }
    else {
      $form['help'] = [
        '#markup' => $this
          ->t('You do not have permission to manage any assignments.'),
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $items = [];
    foreach ($values['schemes'] as $id) {
      $items[$id]['scheme'] = $values['scheme_' . $id];
      $items[$id]['selections'] = $values['active_' . $id];
    }
    foreach ($items as $item) {

      // Add sections.
      $sections = array_filter($item['selections'], function ($val) {
        return !empty($val);
      });
      $sections = array_keys($sections);
      $this->userSectionStorage
        ->addUser($item['scheme'], $this->user, $sections);

      // Remove sections.
      $remove_sections = array_keys(array_filter($item['selections'], function ($val) {
        return empty($val);
      }));
      $this->userSectionStorage
        ->removeUser($item['scheme'], $this->user, $remove_sections);
    }
  }

  /**
   * Gets available form options for this administrative user.
   *
   * @param \Drupal\workbench_access\Entity\AccessSchemeInterface $scheme
   *   The access scheme being processed by the form.
   */
  public function getFormOptions(AccessSchemeInterface $scheme) {
    $options = [];
    $access_scheme = $scheme
      ->getAccessScheme();
    if ($this->manager
      ->userInAll($scheme)) {
      $list = $this->manager
        ->getAllSections($scheme, FALSE);
    }
    else {

      // @TODO: new method needed?
      $list = $this->userSectionStorage
        ->getUserSections($scheme);
      $list = $this
        ->getChildren($access_scheme, $list);
    }
    foreach ($list as $id) {
      if ($section = $access_scheme
        ->load($id)) {
        $options[$id] = str_repeat('-', $section['depth']) . ' ' . $section['label'];
      }
    }
    return $options;
  }

  /**
   * Gets the child sections of a base section.
   *
   * @param \Drupal\workbench_access\AccessControlHierarchyInterface $access_scheme
   *   The access scheme being processed by the form.
   * @param array $values
   *   Defined or selected values.
   *
   * @return array
   *   An array of section ids that this user may see.
   */
  protected function getChildren(AccessControlHierarchyInterface $access_scheme, array $values) {
    $tree = $access_scheme
      ->getTree();
    $children = [];
    foreach ($values as $id) {
      foreach ($tree as $key => $data) {
        if ($id == $key) {
          $children += array_keys($data);
        }
        else {
          foreach ($data as $iid => $item) {
            if ($iid == $id || in_array($id, $item['parents'])) {
              $children[] = $iid;
            }
          }
        }
      }
    }
    return $children;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssignUserForm::$manager protected property Workbnech Access manager.
AssignUserForm::$roleSectionStorage protected property The role section storage service.
AssignUserForm::$schemeStorage protected property The access scheme storage handler.
AssignUserForm::$sectionStorage protected property The section storage handler.
AssignUserForm::$user protected property The user account being edited.
AssignUserForm::$userSectionStorage protected property The user section storage service.
AssignUserForm::access public function Checks access to the form from the route.
AssignUserForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
AssignUserForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
AssignUserForm::getChildren protected function Gets the child sections of a base section.
AssignUserForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AssignUserForm::getFormOptions public function Gets available form options for this administrative user.
AssignUserForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AssignUserForm::__construct public function Constructs the form object.
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.