You are here

class EmailConfirmerResponseForm in Email confirmer 8

Email confirmation response form.

Hierarchy

Expanded class hierarchy of EmailConfirmerResponseForm

File

src/Form/EmailConfirmerResponseForm.php, line 14

Namespace

Drupal\email_confirmer\Form
View source
class EmailConfirmerResponseForm extends EntityConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this
      ->config('email_confirmer.settings')
      ->get('confirmation_response.questions.' . $this->entity
      ->getStatus());
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {

    /** @var \Drupal\email_confirmer\EmailConfirmationInterface $confirmation */
    $confirmation = $this
      ->getEntity();
    return $confirmation
      ->isPending() ? $this
      ->t('Send') : $this
      ->t('OK');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return Url::fromRoute('<front>');
  }

  /**
   * {@inheritdoc}
   */
  public function getFormName() {
    return $this
      ->getFormId();
  }

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

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

    // Skip the response form and positively confirm the confirmation according
    // to the settings.
    if ($this
      ->config('email_confirmer.settings')
      ->get('confirmation_response.skip_confirmation_form')) {
      return $this
        ->skipConfirmationForm($form_state);
    }

    // Build the response form.
    $form = parent::buildForm($form, $form_state);
    unset($form['#process']);
    unset($form['#after_build']);

    // No cancel option needed.
    unset($form['actions']['cancel']);
    if ($this
      ->getEntity()
      ->isPending()) {
      $form['cancel'] = [
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => [
          0 => $this
            ->t('Confirm'),
          1 => $this
            ->t('Cancel'),
        ],
      ];
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {

    /** @var \Drupal\email_confirmer\EmailConfirmationInterface $confirmation */
    $confirmation = $this
      ->getEntity();
    $question = '';
    switch ($confirmation
      ->getStatus()) {
      case 'pending':

        // @todo obfuscate email address if no administer permission, user is anonymous or not owner
        $question = $this
          ->t('Confirm %email', [
          '%email' => $this->entity
            ->label(),
        ]);
        break;
      case 'expired':
        if ($confirmation
          ->isConfirmed() || $confirmation
          ->isCancelled()) {
          $question = $this
            ->t('Already processed');
        }
        else {
          $question = $this
            ->t('Confirmation expired');
        }
        break;
      case 'cancelled':
        $question = $this
          ->t('Confirmation cancelled');
        break;
      case 'confirmed':
        $question = $this
          ->t('Confirmation done');
        break;
    }
    return $question;
  }

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

    // Do nothing if it is not a real response.
    if (!$this
      ->getEntity()
      ->isPending()) {
      $form_state
        ->setRedirectUrl($this
        ->getRedirectUrl('error'));
      return;
    }
    try {
      if ($form_state
        ->getValue('cancel')) {

        // Explicitly cancelled.
        $this
          ->cancelConfirmation($form_state);
      }
      else {

        // Confirmed.
        $this
          ->confirmConfirmation($form_state);
      }
    } catch (InvalidConfirmationStateException $exception) {
      $this
        ->confirmationError($form_state);
    }
  }

  /**
   * Cancels the email confirmation.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @throws \Drupal\email_confirmer\InvalidConfirmationStateException
   *   If confirmation is expired, confirmed or already cancelled.
   */
  protected function cancelConfirmation(FormStateInterface $form_state) {

    /** @var \Drupal\email_confirmer\EmailConfirmationInterface $confirmation */
    $confirmation = $this
      ->getEntity();
    $confirmation
      ->cancel();
    $this
      ->messenger()
      ->addStatus($this
      ->t('Email confirmation cancelled.'));
    $confirmation
      ->save();
    $form_state
      ->setRedirectUrl($this
      ->getRedirectUrl('cancel'));
  }

  /**
   * Confirms the email confirmation.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @throws \Drupal\email_confirmer\InvalidConfirmationStateException
   *   If confirmation is cancelled, expired or already confirmed.
   */
  protected function confirmConfirmation(FormStateInterface $form_state) {

    /** @var \Drupal\email_confirmer\EmailConfirmationInterface $confirmation */
    $confirmation = $this
      ->getEntity();
    if (!$confirmation
      ->confirm($this
      ->getRouteMatch()
      ->getParameter('hash'))) {
      $this
        ->confirmationError($form_state);
      return;
    }
    $this
      ->messenger()
      ->addStatus($this
      ->t('Email confirmation confirmed.'));
    $confirmation
      ->save();
    $form_state
      ->setRedirectUrl($this
      ->getRedirectUrl('confirm'));
  }

  /**
   * Common behaviour when there ware errors in confirmation.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  protected function confirmationError(FormStateInterface $form_state) {
    $this
      ->messenger()
      ->addError($this
      ->t('There was an error processing your email confirmation.'), 'error');
    $form_state
      ->setRedirectUrl($this
      ->getRedirectUrl('error'));
  }

  /**
   * Returns the URL to redirect to after the form is completed or skipped.
   *
   * @param string $operation
   *   Possible values:
   *   - confirm
   *   - cancel
   *   - error
   *   Defines the page that will be redirected to.
   *
   * @return \Drupal\Core\Url
   *   The url to redirect to.
   */
  protected function getRedirectUrl($operation) {

    /** @var \Drupal\email_confirmer\EmailConfirmationInterface $confirmation */
    $confirmation = $this
      ->getEntity();

    // Go to confirmation response URL, response path from settings or front.
    if (!($url = $confirmation
      ->getResponseUrl($operation))) {
      $path = $this
        ->config('email_confirmer.settings')
        ->get('confirmation_response.url.' . $operation) ?: '<front>';
      $url = Url::fromUri('internal:/' . $path);
    }
    return $url;
  }

  /**
   * Skip the response form and positively confirm the confirmation.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   Redirection response according to the confirmation result.
   */
  protected function skipConfirmationForm(FormStateInterface $form_state) {
    try {
      $this
        ->confirmConfirmation($form_state);
    } catch (InvalidConfirmationStateException $exception) {
      $this
        ->confirmationError($form_state);
    }

    // Use RedirectResponse because redirecting with form state is not working
    // inside buildForm.
    $redirect_state = $form_state
      ->getRedirect() ?: $this
      ->getRedirectUrl('error');
    if ($redirect_state instanceof RedirectResponse) {
      $redirect_response = $redirect_state;
    }
    else {
      $redirect_response = new RedirectResponse($redirect_state instanceof Url ? $redirect_state
        ->setAbsolute()
        ->toString() : $redirect_state);
    }
    return $redirect_response;
  }

}

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
EmailConfirmerResponseForm::buildForm public function Form constructor. Overrides EntityConfirmFormBase::buildForm
EmailConfirmerResponseForm::cancelConfirmation protected function Cancels the email confirmation.
EmailConfirmerResponseForm::confirmationError protected function Common behaviour when there ware errors in confirmation.
EmailConfirmerResponseForm::confirmConfirmation protected function Confirms the email confirmation.
EmailConfirmerResponseForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
EmailConfirmerResponseForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides EntityConfirmFormBase::getConfirmText
EmailConfirmerResponseForm::getDescription public function Returns additional text to display as a description. Overrides EntityConfirmFormBase::getDescription
EmailConfirmerResponseForm::getFormId public function Returns a unique string identifying the form. Overrides EntityForm::getFormId
EmailConfirmerResponseForm::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides EntityConfirmFormBase::getFormName
EmailConfirmerResponseForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
EmailConfirmerResponseForm::getRedirectUrl protected function Returns the URL to redirect to after the form is completed or skipped.
EmailConfirmerResponseForm::skipConfirmationForm protected function Skip the response form and positively confirm the confirmation.
EmailConfirmerResponseForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
EntityConfirmFormBase::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions 1
EntityConfirmFormBase::delete public function The delete() method is not used in EntityConfirmFormBase. This overrides the default implementation that redirects to the delete-form confirmation form.
EntityConfirmFormBase::getBaseFormId public function Returns a string identifying the base form. Overrides EntityForm::getBaseFormId
EntityConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText
EntityConfirmFormBase::save public function The save() method is not used in EntityConfirmFormBase. This overrides the default implementation that saves the entity. Overrides EntityForm::save
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::form public function Gets the actual form array to be built. 30
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
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.