You are here

class TeamPermissionsForm in Apigee Edge 8

Provides a form for configuring team-level permissions for all teams.

Based on UserPermissionsForm.

@internal

Hierarchy

Expanded class hierarchy of TeamPermissionsForm

See also

\Drupal\user\Form\UserPermissionsForm

1 string reference to 'TeamPermissionsForm'
apigee_edge_teams.routing.yml in modules/apigee_edge_teams/apigee_edge_teams.routing.yml
modules/apigee_edge_teams/apigee_edge_teams.routing.yml

File

modules/apigee_edge_teams/src/Form/TeamPermissionsForm.php, line 39

Namespace

Drupal\apigee_edge_teams\Form
View source
class TeamPermissionsForm extends FormBase {

  /**
   * The team permission handler.
   *
   * @var \Drupal\apigee_edge_teams\TeamPermissionHandlerInterface
   */
  protected $teamPermissionHandler;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * TeamPermissionsForm constructor.
   *
   * @param \Drupal\apigee_edge_teams\TeamPermissionHandlerInterface $team_permissions
   *   The team permission handler.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(TeamPermissionHandlerInterface $team_permissions, EntityTypeManagerInterface $entity_type_manager) {
    $this->teamPermissionHandler = $team_permissions;
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('apigee_edge_teams.team_permissions'), $container
      ->get('entity_type.manager'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['non_member_team_apps_visible_api_products'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Visible API products on team app add/edit forms for users who are not member of a team'),
      '#description' => $this
        ->t("This configuration allows to limit the visible API products on team app add/edit forms for users who are not a member of the team but still has access to these forms. For example, if a user is not member a team, but it has \"Manage team apps\" site-wide permission then it can create team apps for the team and edit any team apps owned by the team.<br>Suggestion: keep this configuration in sync with the team administrator's API product access settings."),
      '#options' => [
        'public' => $this
          ->t('Public'),
        'private' => $this
          ->t('Private'),
        'internal' => $this
          ->t('Internal'),
      ],
      '#default_value' => $this
        ->config('apigee_edge_teams.team_settings')
        ->get('non_member_team_apps_visible_api_products'),
    ];
    $role_names = [];
    $role_permissions = [];
    $roles = $this
      ->getTeamRoles();

    // The member role should be in the first column.
    $member = $roles['member'];
    unset($roles['member']);
    $roles = [
      'member' => $member,
    ] + $roles;

    // The admin role should be in the last one.
    if (isset($roles['admin'])) {
      $admin = $roles['admin'];
      unset($roles['admin']);
      $roles['admin'] = $admin;
    }
    foreach ($roles as $role_name => $role) {

      // Retrieve role names for columns.
      $role_names[$role_name] = $role
        ->label();

      // Fetch team permission ids for the roles.
      $role_permissions[$role_name] = $role
        ->getPermissions();
    }

    // Store $role_names for use when saving the data.
    $form['role_names'] = [
      '#type' => 'value',
      '#value' => $role_names,
    ];

    // Render role/permission overview:
    $hide_descriptions = system_admin_compact_mode();
    $form['system_compact_link'] = [
      '#id' => FALSE,
      '#type' => 'system_compact_link',
    ];
    $form['permissions'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Permission'),
      ],
      '#id' => 'permissions',
      '#attributes' => [
        'class' => [
          'permissions',
          'js-permissions',
        ],
      ],
      '#sticky' => TRUE,
    ];
    foreach ($role_names as $name) {
      $form['permissions']['#header'][] = [
        'data' => $name,
        'class' => [
          'checkbox',
        ],
      ];
    }
    foreach ($this->teamPermissionHandler
      ->getPermissions() as $permission) {

      // Team permission group name.
      $category_id = preg_replace('/[^A-Za-z0-9_]+/', '_', $permission
        ->getCategory()
        ->getUntranslatedString());
      $form['permissions'][$category_id] = [
        [
          '#wrapper_attributes' => [
            'colspan' => count($role_names) + 1,
            'class' => [
              'group',
            ],
            'id' => Html::getId($category_id),
          ],
          '#markup' => $permission
            ->getCategory(),
        ],
      ];
      $form['permissions'][$permission
        ->getName()]['description'] = [
        '#type' => 'inline_template',
        '#template' => '<div class="permission"><span class="title">{{ title }}</span>{% if description %}<div class="description">{{ description }}</div>{% endif %}</div>',
        '#context' => [
          'title' => $permission
            ->getLabel(),
        ],
      ];

      // Show the permission description.
      if (!$hide_descriptions) {
        $form['permissions'][$permission
          ->getName()]['description']['#context']['description'] = $permission
          ->getDescription() ?? '';
      }
      foreach ($role_names as $rid => $name) {
        $form['permissions'][$permission
          ->getName()][$rid] = [
          '#title' => $permission
            ->getName() . ': ' . $permission
            ->getLabel(),
          '#title_display' => 'invisible',
          '#wrapper_attributes' => [
            'class' => [
              'checkbox',
            ],
          ],
          '#type' => 'checkbox',
          '#default_value' => in_array($permission
            ->getName(), $role_permissions[$rid]) ? 1 : 0,
          '#attributes' => [
            'class' => [
              'rid-' . $rid,
              'js-rid-' . $rid,
            ],
          ],
          '#parents' => [
            $rid,
            $permission
              ->getName(),
          ],
        ];
      }
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save permissions'),
      '#button_type' => 'primary',
    ];
    $form['#attached']['library'][] = 'apigee_edge_teams/permissions';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->configFactory()
      ->getEditable('apigee_edge_teams.team_settings')
      ->set('non_member_team_apps_visible_api_products', array_keys(array_filter($form_state
      ->getValue('non_member_team_apps_visible_api_products', []))))
      ->save();

    /** @var \Drupal\apigee_edge_teams\Entity\Storage\TeamRoleStorageInterface $storage */
    $storage = $this->entityTypeManager
      ->getStorage('team_role');
    foreach ($form_state
      ->getValue('role_names') as $role_name => $name) {
      $storage
        ->changePermissions($role_name, (array) $form_state
        ->getValue($role_name));
    }
    $this
      ->messenger()
      ->addStatus($this
      ->t('The changes have been saved.'));
  }

  /**
   * Gets the team roles to display in this form.
   *
   * @return \Drupal\apigee_edge_teams\Entity\TeamRoleInterface[]
   *   Array of team roles.
   */
  protected function getTeamRoles() : array {
    return $this->entityTypeManager
      ->getStorage('team_role')
      ->loadMultiple();
  }

}

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.
TeamPermissionsForm::$entityTypeManager protected property The entity type manager.
TeamPermissionsForm::$teamPermissionHandler protected property The team permission handler.
TeamPermissionsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
TeamPermissionsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TeamPermissionsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
TeamPermissionsForm::getTeamRoles protected function Gets the team roles to display in this form.
TeamPermissionsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
TeamPermissionsForm::__construct public function TeamPermissionsForm constructor.
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.