You are here

class RequireLoginSettingsForm in Require Login 8.2

Configure Require Login settings for this site.

Hierarchy

Expanded class hierarchy of RequireLoginSettingsForm

1 string reference to 'RequireLoginSettingsForm'
require_login.routing.yml in ./require_login.routing.yml
require_login.routing.yml

File

src/Form/RequireLoginSettingsForm.php, line 15

Namespace

Drupal\require_login\Form
View source
class RequireLoginSettingsForm extends ConfigFormBase {

  /**
   * The routing provider.
   *
   * @var \Drupal\Core\Routing\RouteProvider
   */
  protected $routeProvider;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, RouteProvider $route_provider) {
    parent::__construct($config_factory);
    $this->routeProvider = $route_provider;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('router.route_provider'));
  }

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

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

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

    // Basic settings.
    $form['auth_path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Login path'),
      '#description' => $this
        ->t('Path to the user login page. Default: /user/login'),
      '#default_value' => $config
        ->get('auth_path') ? $config
        ->get('auth_path') : '/user/login',
    ];
    $form['destination_path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Login destination'),
      '#description' => $this
        ->t('Predetermined post-login destination path. Leave blank for the default behavior.'),
      '#default_value' => $config
        ->get('destination_path'),
    ];
    $form['deny_message'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Access denied message'),
      '#description' => $this
        ->t('Show message to user attempting to access a restricted page. Leave blank to disable.'),
      '#default_value' => $config
        ->get('deny_message'),
    ];
    $items = [
      '#theme' => 'item_list',
      '#prefix' => $this
        ->t('Exclude authentication checks on specific paths. <strong>Limit one path per line.</strong>'),
      '#items' => [
        $this
          ->t('Use &lt;front&gt; to exclude the front page.'),
        $this
          ->t('Use internal paths to exclude site pages. <em>I.E. /about/contact</em>'),
        $this
          ->t('Use URL parameters to further refine path matches. <em>I.E. /blog?year=current</em>'),
        $this
          ->t('Use wildcards (*) to match any part of a path. <em>I.E. /shop/*/orders</em>'),
      ],
    ];
    $form['excluded_paths'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Excluded paths'),
      '#description' => render($items),
      '#default_value' => $config
        ->get('excluded_paths'),
    ];
    $node_types = $config
      ->get('excluded_node_types');
    $form['excluded_node_types'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Excluded content types'),
      '#description' => $this
        ->t('Exclude authentication checks on all pages of a specific content type.'),
      '#options' => node_type_get_names(),
      '#multiple' => TRUE,
      '#default_value' => $node_types ? $node_types : [],
    ];

    // Additional settings.
    $form['advanced'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Advanced settings'),
    ];
    $form['advanced']['excluded_403'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Exclude 403 (access denied) page'),
      '#description' => $this
        ->t('Allow unauthenticated access to the 403 (access denied) page.'),
      '#default_value' => $config
        ->get('excluded_403'),
    ];
    $form['advanced']['excluded_404'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Exclude 404 (not found) page'),
      '#description' => $this
        ->t('Allow unauthenticated access to the 404 (not found) page.'),
      '#default_value' => $config
        ->get('excluded_404'),
    ];
    $form['advanced']['excluded_routes'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Excluded route names'),
      '#description' => $this
        ->t('Exclude authentication checks on specific route names. <strong>Limit one path per line.</strong>'),
      '#default_value' => $config
        ->get('excluded_routes'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Process user inputted path.
   *
   * @var string &$path
   *   The path input.
   * @var string $config_key
   *   The configuration key.
   * @var \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  private function processPathInput(&$path, $config_key, FormStateInterface $form_state) {
    $url_parts = parse_url(trim($path));

    // Verify path is valid.
    if (!UrlHelper::isValid($url_parts['path'])) {
      $form_state
        ->setErrorByName($config_key, $this
        ->t('Invalid path: %s', [
        '%s' => $path,
      ]));
      return;
    }

    // Use parsed path in case user inputted schema and/or host.
    $path = $url_parts['path'];
    if (!empty($url_parts['query'])) {
      $path .= '?' . $url_parts['query'];
    }

    // Prepend leading forward slash.
    if (substr($path, 0, 1) !== '/') {
      $path = '/' . $path;
    }
  }

  /**
   * Array filter callback to remove empty elements.
   *
   * @var string $element
   *   The array element.
   *
   * @return bool
   *   TRUE if element should be removed. Otherwise FALSE.
   */
  protected function arrayFilterEmpty($element) {
    return !empty(trim($element));
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Validate login and destination paths.
    $config_keys = [
      'require_login_auth_path',
      'require_login_destination_path',
    ];
    foreach ($config_keys as $config_key) {
      if ($path = $form_state
        ->getValue($config_key)) {
        $this
          ->processPathInput($path, $config_key, $form_state);
        $form_state
          ->setValue($config_key, $path);
      }
    }

    // Validate excluded paths.
    $excluded_paths = preg_split('/\\r\\n|\\r|\\n/', $form_state
      ->getValue('require_login_excluded_paths'));
    $excluded_paths = array_filter($excluded_paths, [
      $this,
      'arrayFilterEmpty',
    ]);
    foreach ($excluded_paths as $key => $path) {
      if (!empty($path) && $path !== '<front>') {
        $this
          ->processPathInput($path, 'require_login_excluded_paths', $form_state);
        $excluded_paths[$key] = $path;
      }
    }
    $form_state
      ->setValue('require_login_excluded_paths', implode(PHP_EOL, $excluded_paths));

    // Validate excluded route names.
    $excluded_routes = preg_split('/\\r\\n|\\r|\\n/', $form_state
      ->getValue('require_login_excluded_routes'));
    $excluded_routes = array_filter($excluded_routes, [
      $this,
      'arrayFilterEmpty',
    ]);
    if (!empty($excluded_routes)) {
      $valid_route_names = $this->routeProvider
        ->getRoutesByNames($excluded_routes);
      if ($invalid_route_names = array_diff($excluded_routes, array_keys($valid_route_names))) {
        $items = [
          '#theme' => 'item_list',
          '#prefix' => $this
            ->t('Missing route names detected. You may remove them if the related modules will not be installed.'),
          '#items' => $invalid_route_names,
        ];
        $this
          ->messenger()
          ->addWarning(render($items));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->config('require_login.config')
      ->set('auth_path', $form_state
      ->getValue('auth_path'))
      ->set('destination_path', $form_state
      ->getValue('destination_path'))
      ->set('deny_message', $form_state
      ->getValue('deny_message'))
      ->set('excluded_403', $form_state
      ->getValue('excluded_403'))
      ->set('excluded_404', $form_state
      ->getValue('excluded_404'))
      ->set('excluded_paths', $form_state
      ->getValue('excluded_paths'))
      ->set('excluded_node_types', $form_state
      ->getValue('excluded_node_types'))
      ->set('excluded_routes', $form_state
      ->getValue('excluded_routes'))
      ->save();

    // Flush caches so changes take immediate effect.
    drupal_flush_all_caches();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
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.
RequireLoginSettingsForm::$routeProvider protected property The routing provider.
RequireLoginSettingsForm::arrayFilterEmpty protected function Array filter callback to remove empty elements.
RequireLoginSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
RequireLoginSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
RequireLoginSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
RequireLoginSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RequireLoginSettingsForm::processPathInput private function Process user inputted path.
RequireLoginSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
RequireLoginSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
RequireLoginSettingsForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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.