You are here

class ImceSettingsForm in IMCE 8.2

Same name and namespace in other branches
  1. 8 src/Form/ImceSettingsForm.php \Drupal\imce\Form\ImceSettingsForm

Imce settings form.

Hierarchy

Expanded class hierarchy of ImceSettingsForm

1 file declares its use of ImceSettingsForm
ImceSettingsFormTest.php in tests/src/Kernel/Form/ImceSettingsFormTest.php

File

src/Form/ImceSettingsForm.php, line 17

Namespace

Drupal\imce\Form
View source
class ImceSettingsForm extends ConfigFormBase {
  use ImceSettersTrait;

  /**
   * Manages entity type plugin definitions.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The system file config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $configSystemFile;

  /**
   * Provides a StreamWrapper manager.
   *
   * @var Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
   */
  protected $streamWrapperManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    /**
     * @var \Drupal\imce\Form\ImceSettingsForm
     */
    $instance = parent::create($container);
    $instance
      ->setConfigSystemFile($container
      ->get('config.factory')
      ->get('system.file'));
    $instance
      ->setEntityTypeManager($container
      ->get('entity_type.manager'));
    $instance
      ->setStreamWrapperManager($container
      ->get('stream_wrapper_manager'));
    return $instance;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'imce.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('imce.settings');
    $form['roles_profiles'] = $this
      ->buildRolesProfilesTable($config
      ->get('roles_profiles') ?: []);

    // Common settings container.
    $form['common'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Common settings'),
    ];
    $form['common']['abs_urls'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable absolute URLs'),
      '#description' => $this
        ->t('Make the file manager return absolute file URLs to other applications.'),
      '#default_value' => $config
        ->get('abs_urls'),
    ];
    $form['common']['admin_theme'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Use admin theme for IMCE paths'),
      '#default_value' => $config
        ->get('admin_theme'),
      '#description' => $this
        ->t('If you have user interface issues with the active theme you may consider switching to admin theme.'),
    ];
    $form['#attached']['library'][] = 'imce/drupal.imce.admin';
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('imce.settings');

    // Absolute URLs.
    $config
      ->set('abs_urls', $form_state
      ->getValue('abs_urls'));

    // Admin theme.
    $config
      ->set('admin_theme', $form_state
      ->getValue('admin_theme'));
    $roles_profiles = $form_state
      ->getValue('roles_profiles');

    // Filter empty values.
    foreach ($roles_profiles as $rid => &$profiles) {
      if (!($profiles = array_filter($profiles))) {
        unset($roles_profiles[$rid]);
      }
    }
    $config
      ->set('roles_profiles', $roles_profiles);
    $config
      ->save();

    // Warn about anonymous access.
    if (!empty($roles_profiles[RoleInterface::ANONYMOUS_ID])) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('You have enabled anonymous access to the file manager. Please make sure this is not a misconfiguration.'), 'warning');
    }
    parent::submitForm($form, $form_state);
  }

  /**
   * Get the profile options.
   *
   * @return array
   *   The profile options.
   */
  public function getProfileOptions() {

    // Prepare profile options.
    $options = [
      '' => '-' . $this
        ->t('None') . '-',
    ];
    foreach ($this->entityTypeManager
      ->getStorage('imce_profile')
      ->loadMultiple() as $pid => $profile) {
      $options[$pid] = $profile
        ->label();
    }
    return $options;
  }

  /**
   * Build header.
   *
   * @return array
   *   Array of headers items.
   */
  public function buildHeaderProfilesTable() : array {
    $wrappers = $this->streamWrapperManager
      ->getNames(StreamWrapperInterface::WRITE_VISIBLE);
    $imce_url = Url::fromRoute('imce.page')
      ->toString();
    $rp_table['#header'] = [
      $this
        ->t('Role'),
    ];
    $default = $this->configSystemFile
      ->get('default_scheme');
    foreach ($wrappers as $scheme => $name) {
      $url = $scheme === $default ? $imce_url : $imce_url . '/' . $scheme;
      $rp_table['#header'][]['data'] = [
        '#markup' => '<a href="' . $url . '">' . Html::escape($name) . '</a>',
      ];
    }
    return $rp_table;
  }

  /**
   * Create tables profiles rows.
   */
  public function buildRowsProfilesTables($roles, $roles_profiles, $wrappers) {

    // Prepare roles.
    $rp_table = [];
    foreach ($roles as $rid => $role) {
      $rp_table[$rid]['role_name'] = [
        '#plain_text' => $role
          ->label(),
      ];
      foreach ($wrappers as $scheme => $name) {
        $rp_table[$rid][$scheme] = [
          '#type' => 'select',
          '#options' => $this
            ->getProfileOptions(),
          '#default_value' => isset($roles_profiles[$rid][$scheme]) ? $roles_profiles[$rid][$scheme] : '',
        ];
      }
    }
    return $rp_table;
  }

  /**
   * Returns roles-profiles table.
   */
  public function buildRolesProfilesTable(array $roles_profiles) {
    $rp_table = [
      '#type' => 'table',
    ];
    $roles = user_roles();
    $wrappers = $this->streamWrapperManager
      ->getNames(StreamWrapperInterface::WRITE_VISIBLE);
    $imce_url = Url::fromRoute('imce.page')
      ->toString();
    $rp_table += $this
      ->buildHeaderProfilesTable($wrappers);
    $rp_table += $this
      ->buildRowsProfilesTables($roles, $roles_profiles, $wrappers);

    // Add description.
    $rp_table['#prefix'] = '<h3>' . $this
      ->t('Role-profile assignments') . '</h3>';
    $rp_table['#suffix'] = '<div class="description">' . $this
      ->t('Assign configuration profiles to user roles for available file systems. Users with multiple roles get the bottom most profile.') . ' ' . $this
      ->t('The default file system %name is accessible at :url path.', [
      '%name' => $wrappers[$this->configSystemFile
        ->get('default_scheme')],
      ':url' => $imce_url,
    ]) . '</div>';
    return $rp_table;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration 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::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
ImceSettersTrait::setConfigSystemFile protected function Set config system file.
ImceSettersTrait::setEntityTypeManager protected function Set entity type manager.
ImceSettersTrait::setStreamWrapperManager protected function Set the stream wrapper manager.
ImceSettingsForm::$configSystemFile protected property The system file config. Overrides ImceSettersTrait::$configSystemFile
ImceSettingsForm::$entityTypeManager protected property Manages entity type plugin definitions. Overrides ImceSettersTrait::$entityTypeManager
ImceSettingsForm::$streamWrapperManager protected property Provides a StreamWrapper manager. Overrides ImceSettersTrait::$streamWrapperManager
ImceSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
ImceSettingsForm::buildHeaderProfilesTable public function Build header.
ImceSettingsForm::buildRolesProfilesTable public function Returns roles-profiles table.
ImceSettingsForm::buildRowsProfilesTables public function Create tables profiles rows.
ImceSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
ImceSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ImceSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ImceSettingsForm::getProfileOptions public function Get the profile options.
ImceSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
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.