You are here

class DisclaimerEmailMatchForm in Disclaimer 8

Class DisclaimerEmailMatchForm.

Hierarchy

Expanded class hierarchy of DisclaimerEmailMatchForm

File

src/Form/DisclaimerEmailMatchForm.php, line 18

Namespace

Drupal\disclaimer\Form
View source
class DisclaimerEmailMatchForm extends FormBase {

  /**
   * Settings of related block.
   *
   * @var array
   */
  public $blockSettings = [];

  /**
   * Creates an DisclaimerEmailMatchForm object.
   *
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   */
  public function __construct(RendererInterface $renderer) {
    $this->renderer = $renderer;
  }

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('renderer'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $ajax_wrapper_id = Html::getUniqueId('box-container');
    $form['#prefix'] = '<div id="' . $ajax_wrapper_id . '">';
    $form['#suffix'] = '</div>';
    $form['email'] = [
      '#type' => 'email',
      '#title' => $this
        ->t('E-mail'),
      '#weight' => 10,
    ];
    $form['block_id'] = [
      '#type' => 'hidden',
      '#default_value' => '',
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
      '#weight' => 20,
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'wrapper' => $ajax_wrapper_id,
      ],
    ];
    $form['leave'] = [
      '#type' => 'button',
      '#name' => 'leave',
      '#value' => $this
        ->t('Leave'),
      '#weight' => 30,
      '#ajax' => [
        'callback' => '::leaveForm',
        'wrapper' => $ajax_wrapper_id,
      ],
    ];
    return $form;
  }

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

    // Don't validate anything when leaving.
    if ($form_state
      ->getTriggeringElement()['#name'] == 'leave') {
      return;
    }
    parent::validateForm($form, $form_state);
    $this
      ->populateSettings($form, $form_state);

    // Block ID is essential for this form.
    if (empty($form_state
      ->getValue('block_id')) || empty($this->blockSettings['email_validation_fail'])) {

      // Provide some feedback.
      $form_state
        ->setErrorByName('', $this
        ->t('Unable to verify the e-mail.'));

      // But this is really backend error.
      // Hint: Hidden block_id value needs to be set in code.
      $this
        ->logger('disclaimer')
        ->error('disclaimer_email_match_form needs to be provided with block_id');
      return;
    }

    // E-mail is required.
    // Can't mark form element as required as it results
    // in error message when "Leave" button is used.
    if (empty($form_state
      ->getValue('email'))) {
      $form_state
        ->setErrorByName('email', $this
        ->t('E-mail field is required.'));
    }

    // Validate e-mail against the list.
    if (!$this
      ->validateEmail($form, $form_state)) {
      $form_state
        ->setErrorByName('email', $this->blockSettings['email_validation_fail']);
    }
  }

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

    // Save the success in cookie.
    setcookie('disclaimer_email_' . Html::escape($this->blockSettings['machine_name']), 1, time() + $this->blockSettings['max_age']);

    // @ToDo: Dispatch an Event to offer the e-mail to other modules.
  }

  /**
   * {@inheritdoc}
   */
  public function leaveForm(array &$form, FormStateInterface $form_state) {
    $this
      ->populateSettings($form, $form_state);
    $response = new AjaxResponse();
    $response
      ->addCommand(new RedirectCommand($this->blockSettings['redirect']));
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    $status_messages = [
      '#type' => 'status_messages',
    ];
    if ($form_state
      ->hasAnyErrors()) {

      // Show form with errors.
      $form['#prefix'] .= $this->renderer
        ->renderRoot($status_messages);
      return $form;
    }
    else {

      // All good. Return command to close the UI dialog.
      $response = new AjaxResponse();
      $response
        ->addCommand(new InvokeCommand('.disclaimer_email__challenge', 'dialog', [
        'close',
      ]));
      return $response;
    }
  }

  /**
   * {@inheritdoc}
   */
  private function validateEmail(array $form, FormStateInterface $form_state) {

    // Reject address in case we don't have required config.
    $this
      ->populateSettings($form, $form_state);
    if (!isset($this->blockSettings['allowed_emails'])) {
      return FALSE;
    }

    // Explode and trim spaces and line breaks.
    $allowed_emails = array_map('trim', explode("\n", $this->blockSettings['allowed_emails']));

    // Check email against the list.
    $provided_email = $form_state
      ->getValue('email');
    foreach ($allowed_emails as $allowed_email) {
      if (fnmatch($allowed_email, $provided_email, FNM_CASEFOLD)) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  private function populateSettings(array $form, FormStateInterface $form_state) {
    $block = Block::load($form_state
      ->getValue('block_id'));

    // Exit in case we don't have required block.
    if ($block) {
      $this->blockSettings = $block
        ->get('settings');
    }
  }

}

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
DisclaimerEmailMatchForm::$blockSettings public property Settings of related block.
DisclaimerEmailMatchForm::ajaxSubmit public function
DisclaimerEmailMatchForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
DisclaimerEmailMatchForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DisclaimerEmailMatchForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DisclaimerEmailMatchForm::leaveForm public function
DisclaimerEmailMatchForm::populateSettings private function
DisclaimerEmailMatchForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DisclaimerEmailMatchForm::validateEmail private function
DisclaimerEmailMatchForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
DisclaimerEmailMatchForm::__construct public function Creates an DisclaimerEmailMatchForm object.
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 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.