You are here

class ProtectedPagesAddForm in Protected Pages 8

Provides an add protected page form.

Hierarchy

Expanded class hierarchy of ProtectedPagesAddForm

1 string reference to 'ProtectedPagesAddForm'
protected_pages.routing.yml in ./protected_pages.routing.yml
protected_pages.routing.yml

File

src/Form/ProtectedPagesAddForm.php, line 18

Namespace

Drupal\protected_pages\Form
View source
class ProtectedPagesAddForm extends FormBase {

  /**
   * The protected pages storage service.
   *
   * @var \Drupal\protected_pages\ProtectedPagesStorage
   */
  protected $protectedPagesStorage;

  /**
   * The path validator.
   *
   * @var \Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * Provides the password hashing service object.
   *
   * @var \Drupal\Core\Password\PasswordInterface
   */
  protected $password;

  /**
   * Provides messenger service.
   *
   * @var \Drupal\Core\Messenger\Messenger
   */
  protected $messenger;

  /**
   * Path alias manager.
   *
   * @var \Drupal\path_alias\AliasManager
   */
  protected $aliasManager;

  /**
   * Constructs a new ProtectedPagesAddForm.
   *
   * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
   *   The path validator.
   * @param \Drupal\Core\Password\PasswordInterface $password
   *   The password hashing service.
   * @param \Drupal\protected_pages\ProtectedPagesStorage $protectedPagesStorage
   *   The protected pages storage.
   * @param \Drupal\Core\Messenger\Messenger $messenger
   *   The messenger service.
   * @param \Drupal\path_alias\AliasManager $aliasManager
   *   The path alias manager service.
   */
  public function __construct(PathValidatorInterface $path_validator, PasswordInterface $password, ProtectedPagesStorage $protectedPagesStorage, Messenger $messenger, AliasManager $aliasManager) {
    $this->pathValidator = $path_validator;
    $this->password = $password;
    $this->protectedPagesStorage = $protectedPagesStorage;
    $this->messenger = $messenger;
    $this->aliasManager = $aliasManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('path.validator'), $container
      ->get('password'), $container
      ->get('protected_pages.storage'), $container
      ->get('messenger'), $container
      ->get('path_alias.manager'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['rules_list'] = [
      '#title' => $this
        ->t('Add Protected Page relative path and password.'),
      '#type' => 'details',
      '#description' => $this
        ->t('Please enter the relative path and its corresponding
    password. When user opens this url, they will asked to enter password to
    view this page. For example, "/node/5", "/new-events" etc.'),
      '#open' => TRUE,
    ];
    $form['rules_list']['path'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Relative path'),
      '#description' => $this
        ->t('Enter relative Drupal path. For example, "/node/5", "new-events" etc.'),
      '#required' => TRUE,
    ];
    $form['rules_list']['password'] = [
      '#type' => 'password_confirm',
      '#size' => 25,
      '#required' => TRUE,
    ];
    $form['rules_list']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $entered_path = rtrim(trim($form_state
      ->getValue('path')), " \\/");
    if (substr($entered_path, 0, 1) != '/') {
      $form_state
        ->setErrorByName('path', $this
        ->t('The path needs to start with a slash.'));
    }
    else {
      $normal_path = $this->aliasManager
        ->getPathByAlias($form_state
        ->getValue('path'));
      $path_alias = mb_strtolower($this->aliasManager
        ->getAliasByPath($form_state
        ->getValue('path')));
      if (!$this->pathValidator
        ->isValid($normal_path)) {
        $form_state
          ->setErrorByName('path', $this
          ->t('Please enter a correct path!'));
      }
      $fields = [
        'pid',
      ];
      $conditions = [];
      $conditions['or'][] = [
        'field' => 'path',
        'value' => $normal_path,
        'operator' => '=',
      ];
      $conditions['or'][] = [
        'field' => 'path',
        'value' => $path_alias,
        'operator' => '=',
      ];
      $pid = $this->protectedPagesStorage
        ->loadProtectedPage($fields, $conditions, TRUE);
      if ($pid) {
        $form_state
          ->setErrorByName('path', $this
          ->t('Duplicate path entry is not allowed. There is already a path or its alias exists.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $page_data = [
      'password' => $this->password
        ->hash(Html::escape($form_state
        ->getValue('password'))),
      'path' => Html::escape($form_state
        ->getValue('path')),
    ];
    $pid = $this->protectedPagesStorage
      ->insertProtectedPage($page_data);
    if ($pid) {
      $this->messenger
        ->addMessage($this
        ->t('The protected page settings have been successfully saved.'));
    }
    drupal_flush_all_caches();
    $form_state
      ->setRedirect('protected_pages_list');
  }

}

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.
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 public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ProtectedPagesAddForm::$aliasManager protected property Path alias manager.
ProtectedPagesAddForm::$messenger protected property Provides messenger service. Overrides MessengerTrait::$messenger
ProtectedPagesAddForm::$password protected property Provides the password hashing service object.
ProtectedPagesAddForm::$pathValidator protected property The path validator.
ProtectedPagesAddForm::$protectedPagesStorage protected property The protected pages storage service.
ProtectedPagesAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ProtectedPagesAddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ProtectedPagesAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ProtectedPagesAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ProtectedPagesAddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ProtectedPagesAddForm::__construct public function Constructs a new ProtectedPagesAddForm.
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.