You are here

class ParserOperationForm in Markdown 8.2

Provides a confirmation form to disable a parser.

@internal

Hierarchy

Expanded class hierarchy of ParserOperationForm

1 string reference to 'ParserOperationForm'
markdown.routing.yml in ./markdown.routing.yml
markdown.routing.yml

File

src/Form/ParserOperationForm.php, line 18

Namespace

Drupal\markdown\Form
View source
class ParserOperationForm extends ConfirmFormBase {
  protected $operationConfigNames = [
    'default' => 'markdown.settings',
    'disable' => 'markdown.parser.%s',
    'enable' => 'markdown.parser.%s',
  ];

  /**
   * The operation to perform.
   *
   * @var string
   */
  protected $operation;

  /**
   * The operation method to invoke.
   *
   * @var callable
   */
  protected $operationMethod;

  /**
   * The markdown parser.
   *
   * @var \Drupal\markdown\Plugin\Markdown\ParserInterface
   */
  protected $parser;

  /**
   * An array of variables to use in translations.
   *
   * @var string[]
   */
  protected $variables;

  /**
   * Creates a URL with the appropriate CSRF token for a parser operation.
   *
   * @param \Drupal\markdown\Plugin\Markdown\ParserInterface $parser
   *   The parser to perform an operation on.
   * @param string $operation
   *   The operation to perform.
   *
   * @return \Drupal\Core\Url
   *   A parser operation Url object.
   */
  public static function createOperationUrl(ParserInterface $parser, $operation) {

    // Because this is redirecting to a CSRF access controlled route, this
    // needs the correct token added to the route's query option. Core
    // usually does this automatically, but its based on this current form
    // not the redirected route. So it must be manually set here.
    $url = Url::fromRoute('markdown.parser.operation', [
      'parser' => $parser,
      'operation' => $operation,
    ]);
    $token = \Drupal::csrfToken()
      ->get($url
      ->getInternalPath());
    $options = $url
      ->getOptions();
    $options['query']['token'] = $token;
    $url
      ->setOptions($options);
    return $url;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    switch ($this->operation) {
      case 'default':
        return $this
          ->t('Are you sure you want to set %parser as the default markdown parser?', [
          '@operation' => $this->operation,
          '%parser' => $this->parser
            ->getLabel(FALSE),
        ]);
    }
    return $this
      ->t('Are you sure you want to @operation the %parser markdown parser?', [
      '@operation' => $this->operation,
      '%parser' => $this->parser
        ->getLabel(FALSE),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Confirm Operation');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    switch ($this->operation) {
      case 'default':
        return $this
          ->t('Set as default');
    }
    return $this
      ->t(ucfirst($this->operation));
  }

  /**
   * Retrieves the success message to show after the operation has finished.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup
   *   The success message.
   */
  public function getSuccessMessage() {
    $variables = [
      '@action' => substr($this->operation, -1, 1) === 'e' ? $this
        ->t($this->operation . 'd') : $this->operation . 'ed',
      '@operation' => $this->operation,
      '%parser' => $this->parser
        ->getLabel(FALSE),
      '@parser_id' => $this->parser
        ->getPluginId(),
    ];
    switch ($this->operation) {
      case 'default':
        return $this
          ->t('%parser was set as the default markdown parser.', $variables);
    }
    return $this
      ->t('The markdown parser %parser was @action.', $variables);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('markdown.overview');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ParserInterface $parser = NULL, $operation = NULL) {
    $this
      ->initializeOperation($parser, $operation);
    $form = parent::buildForm($form, $form_state);

    // Allow the cancel button to simply close the dialog.
    if (!empty(\Drupal::request()
      ->get('_drupal_ajax'))) {
      $form['actions']['cancel']['#attributes']['class'][] = 'dialog-cancel';
    }
    return $form;
  }

  /**
   * Initializes the operation.
   *
   * @param \Drupal\markdown\Plugin\Markdown\ParserInterface $parser
   *   The parser being operated on.
   * @param string $operation
   *   The operation to perform.
   */
  protected function initializeOperation(ParserInterface $parser, $operation) {
    $this->operation = $operation;
    $this->parser = $parser;
    $this->variables = [
      '@action' => substr($this->operation, -1, 1) === 'e' ? $this
        ->t($this->operation . 'd') : $this->operation . 'ed',
      '@operation' => $this->operation,
      '%parser' => $this->parser
        ->getLabel(FALSE),
      '@parser_id' => $this->parser
        ->getPluginId(),
    ];
    $converter = new CamelCaseToSnakeCaseNameConverter();
    $method = $converter
      ->denormalize("operation_{$operation}");
    if (!method_exists($this, $method)) {
      throw new NotFoundHttpException();
    }
    $this->operationMethod = [
      $this,
      $method,
    ];
  }

  /**
   * Controller for the "markdown.parser.operation" route.
   *
   * @param \Drupal\markdown\Plugin\Markdown\ParserInterface $parser
   *   The parser being operated on.
   * @param string $operation
   *   The operation to perform.
   *
   * @return array|\Symfony\Component\HttpFoundation\Response|void
   *   A render array or response object.
   */
  public function executeOperation(ParserInterface $parser, $operation) {
    $this
      ->initializeOperation($parser, $operation);

    // Retrieve the Config object for the parser.
    $configName = sprintf(isset($this->operationConfigNames[$this->operation]) ? $this->operationConfigNames[$this->operation] : 'markdown.parser.%s', $this->parser
      ->getPluginId());
    $config = $this
      ->configFactory()
      ->getEditable($configName);

    // Execute the operation, passing the config as its only parameter.
    $callable = $this->operationMethod;
    $response = $callable($config);
    $this
      ->logger('markdown')
      ->notice('Performed operation (@operation) on parser %parser (@parser_id).', [
      '@operation' => $this->operation,
      '%parser' => $this->parser
        ->getLabel(FALSE),
      '@parser_id' => $this->parser
        ->getPluginId(),
    ]);
    if ($message = $this
      ->getSuccessMessage()) {
      drupal_set_message($message);
    }

    // Allow the operation to override the response.
    if ($response) {
      return $response;
    }

    // Otherwise, redirect to the overview page.
    return $this
      ->redirect('markdown.overview');
  }

  /**
   * Retrieves an editable Config object for the parser.
   *
   * @return \Drupal\Core\Config\Config
   *   The Parser Config object.
   */
  protected function getParserConfig() {
    return $this
      ->configFactory()
      ->getEditable('markdown.parser.' . $this->parser
      ->getPluginId());
  }

  /**
   * Magic method for the "default" operation.
   *
   * @param \Drupal\Core\Config\Config $config
   *   The editable parser Config object.
   *
   * @see \Drupal\markdown\Form\ParserOperationForm::initializeOperation
   */
  protected function operationDefault(Config $config) {
    $config
      ->set('default_parser', $this->parser
      ->getPluginId())
      ->save();
  }

  /**
   * Magic method for the "disable" operation.
   *
   * @param \Drupal\Core\Config\Config $config
   *   The editable parser Config object.
   *
   * @see \Drupal\markdown\Form\ParserOperationForm::initializeOperation
   */
  protected function operationDisable(Config $config) {
    $config
      ->set('enabled', FALSE)
      ->save();
  }

  /**
   * Magic method for the "enable" operation.
   *
   * @param \Drupal\Core\Config\Config $config
   *   The editable parser Config object.
   *
   * @see \Drupal\markdown\Form\ParserOperationForm::initializeOperation
   */
  public function operationEnable(Config $config) {
    $config
      ->set('enabled', TRUE)
      ->save();
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->operation) {
      $url = static::createOperationUrl($this->parser, $this->operation);
    }
    else {
      $url = $this
        ->getCancelUrl();
    }
    $form_state
      ->setRedirectUrl($url);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 1
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
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::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.
ParserOperationForm::$operation protected property The operation to perform.
ParserOperationForm::$operationConfigNames protected property
ParserOperationForm::$operationMethod protected property The operation method to invoke.
ParserOperationForm::$parser protected property The markdown parser.
ParserOperationForm::$variables protected property An array of variables to use in translations.
ParserOperationForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
ParserOperationForm::createOperationUrl public static function Creates a URL with the appropriate CSRF token for a parser operation.
ParserOperationForm::executeOperation public function Controller for the "markdown.parser.operation" route.
ParserOperationForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
ParserOperationForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
ParserOperationForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
ParserOperationForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ParserOperationForm::getParserConfig protected function Retrieves an editable Config object for the parser.
ParserOperationForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
ParserOperationForm::getSuccessMessage public function Retrieves the success message to show after the operation has finished.
ParserOperationForm::initializeOperation protected function Initializes the operation.
ParserOperationForm::operationDefault protected function Magic method for the "default" operation.
ParserOperationForm::operationDisable protected function Magic method for the "disable" operation.
ParserOperationForm::operationEnable public function Magic method for the "enable" operation.
ParserOperationForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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.