You are here

class PurgeBlockForm in Purge 8.3

End-user form for \Drupal\purge_ui\Plugin\Block\PurgeBlock.

Hierarchy

Expanded class hierarchy of PurgeBlockForm

1 file declares its use of PurgeBlockForm
PurgeBlock.php in modules/purge_ui/src/Plugin/Block/PurgeBlock.php

File

modules/purge_ui/src/Form/PurgeBlockForm.php, line 23

Namespace

Drupal\purge_ui\Form
View source
class PurgeBlockForm extends FormBase {

  /**
   * The form's configuration array, which determines how and what we purge.
   *
   * @var string[]
   */
  protected $config;

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

  /**
   * The 'purge_ui_block_processor' plugin.
   *
   * @var null|\Drupal\purge\Plugin\Purge\Processor\ProcessorInterface
   */
  protected $processor;

  /**
   * The 'purge_ui_block_queuer' plugin.
   *
   * @var null|\Drupal\purge\Plugin\Purge\Queuer\QueuerInterface
   */
  protected $queuer;

  /**
   * The 'purge.purgers' service.
   *
   * @var \Drupal\purge\Plugin\Purge\Purger\PurgersServiceInterface
   */
  protected $purgePurgers;

  /**
   * The 'purge.invalidation.factory' service.
   *
   * @var \Drupal\purge\Plugin\Purge\Invalidation\InvalidationsServiceInterface
   */
  protected $purgeInvalidationFactory;

  /**
   * The 'purge.queue' service.
   *
   * @var \Drupal\purge\Plugin\Purge\Queue\QueueServiceInterface
   */
  protected $purgeQueue;

  /**
   * Construct a PurgeBlockForm object.
   *
   * @param string[] $config
   *   The form's configuration array, which determines how and what we purge.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\purge\Plugin\Purge\Processor\ProcessorsServiceInterface $purge_processors
   *   The purge processors service.
   * @param \Drupal\purge\Plugin\Purge\Purger\PurgersServiceInterface $purge_purgers
   *   The purge purgers service.
   * @param \Drupal\purge\Plugin\Purge\Invalidation\InvalidationsServiceInterface $purge_invalidation_factory
   *   The purge invalidations factory service.
   * @param \Drupal\purge\Plugin\Purge\Queue\QueueServiceInterface $purge_queue
   *   The purge queue service.
   * @param \Drupal\purge\Plugin\Purge\Queuer\QueuersServiceInterface $purge_queuers
   *   The purge queuers service.
   */
  public final function __construct(array $config, MessengerInterface $messenger, ProcessorsServiceInterface $purge_processors, PurgersServiceInterface $purge_purgers, InvalidationsServiceInterface $purge_invalidation_factory, QueueServiceInterface $purge_queue, QueuersServiceInterface $purge_queuers) {
    if (is_null($config)) {
      throw new \LogicException('\\Drupal\\purge_ui\\Form\\PurgeBlockForm should be directly instantiated with block configuration passed in.');
    }
    $this->config = $config;
    $this->messenger = $messenger;
    $this->processor = $purge_processors
      ->get('purge_ui_block_processor');
    $this->queuer = $purge_queuers
      ->get('purge_ui_block_queuer');
    $this->purgePurgers = $purge_purgers;
    $this->purgeInvalidationFactory = $purge_invalidation_factory;
    $this->purgeQueue = $purge_queue;
  }

  /**
   * {@inheritdoc}
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The dependency injection container.
   * @param string[] $config
   *   The form's configuration array, which determines how and what we purge.
   */
  public static function create(ContainerInterface $container, array $config = NULL) {
    return new static($config, $container
      ->get('messenger'), $container
      ->get('purge.processors'), $container
      ->get('purge.purgers'), $container
      ->get('purge.invalidation.factory'), $container
      ->get('purge.queue'), $container
      ->get('purge.queuers'));
  }

  /**
   * Gather information for the invalidation objects to be queued/purged.
   *
   * @return string[]
   *   List of expressions to be queued/purged as invalidation objects.
   */
  protected function gatherInvalidationsData() {
    $request = $this
      ->getRequest();
    $expressions = [];
    switch ($this->config['type']) {
      case 'url':
        $expressions[] = $request
          ->getUriForPath($request
          ->getRequestUri());
        $expressions[] = $request
          ->getUri();
        $expressions[] = str_replace('?' . $request
          ->getQueryString(), '', $expressions[1]);
        break;
      case 'path':
        $expressions[] = ltrim($request
          ->getRequestUri(), '/');
        $expressions[] = explode('?', $expressions[0])[0];
        break;
      case 'everything':
        $expressions[] = NULL;
        break;
    }
    return array_unique($expressions);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'purge_ui.purge_' . $this->config['purge_block_id'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form_state
      ->addBuildInfo('expressions', $this
      ->gatherInvalidationsData());
    $form = [];
    if ($this->config['execution'] === 'direct' && !$this->processor) {
      $this->messenger
        ->addError($this
        ->t('Please contact your site administrator to enable the block processor plugin.'));
      return [
        'messages' => [
          '#type' => 'status_messages',
        ],
      ];
    }
    if ($this->config['execution'] === 'queue' && !$this->queuer) {
      $this->messenger
        ->addError($this
        ->t('Please contact your site administrator to enable the block queuer plugin.'));
      return [
        'messages' => [
          '#type' => 'status_messages',
        ],
      ];
    }
    if (!empty($this->config['description'])) {
      $form['description'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->config['description'],
      ];
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->config['submit_label'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (empty($form_state
      ->getBuildInfo()['expressions'])) {
      $form_state
        ->setErrorByName('submit', $this
        ->t('Invalid form submission.'));
    }
    if ($this->config['execution'] === 'direct' && !$this->processor) {
      $form_state
        ->setErrorByName('submit', $this
        ->t('Please contact your site administrator to enable the block processor plugin.'));
    }
    if ($this->config['execution'] === 'queue' && !$this->queuer) {
      $form_state
        ->setErrorByName('submit', $this
        ->t('Please contact your site administrator to enable the block queuer plugin.'));
    }
  }

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

    // Instantiate the invalidation objects with the prepared expressions.
    $invalidations = [];
    foreach ($form_state
      ->getBuildInfo()['expressions'] as $expression) {
      try {
        $invalidations[] = $this->purgeInvalidationFactory
          ->get($this->config['type'], $expression);
      } catch (TypeUnsupportedException $e) {
        $this->messenger
          ->addError($this
          ->t("No purger supports the type '@type', please install one!", [
          '@type' => $this->config['type'],
        ]));
        return;
      }
    }

    // Queue execution is the easiest, as it always succeeds.
    if ($this->config['execution'] === 'queue') {
      $this->purgeQueue
        ->add($this->queuer, $invalidations);
      $this->messenger
        ->addStatus($this
        ->t('Please wait for the queue to be processed!'));
    }
    else {
      try {
        $this->purgePurgers
          ->invalidate($this->processor, $invalidations);

        // Prepare and issue messages for each individual invalidation object.
        foreach ($invalidations as $invalidation) {
          $object = $invalidation
            ->getType();
          if (!is_null($invalidation
            ->getExpression())) {
            $object = $this
              ->t('@object with expression "@expr"', [
              '@object' => $invalidation
                ->getType(),
              '@expr' => (string) $invalidation
                ->getExpression(),
            ]);
          }
          if ($invalidation
            ->getState() === InvStatesInterface::SUCCEEDED) {
            $this->messenger
              ->addMessage($this
              ->t('Succesfully cleared @object.', [
              '@object' => $object,
            ]));
          }
          elseif ($invalidation
            ->getState() === InvStatesInterface::PROCESSING) {
            $this->messenger
              ->addWarning($this
              ->t('Requested to clear multistep object of type @object!', [
              '@object' => $object,
            ]));
          }
          else {
            $this->messenger
              ->addError($this
              ->t('Failed to clear @object!', [
              '@object' => $object,
            ]));
          }
        }
      } catch (DiagnosticsException $e) {
        $this->messenger
          ->addError($e
          ->getMessage());
      } catch (CapacityException $e) {
        $this->messenger
          ->addError($e
          ->getMessage());
      } catch (LockException $e) {
        $this->messenger
          ->addError($e
          ->getMessage());
      }
    }
  }

}

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.
PurgeBlockForm::$config protected property The form's configuration array, which determines how and what we purge.
PurgeBlockForm::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
PurgeBlockForm::$processor protected property The 'purge_ui_block_processor' plugin.
PurgeBlockForm::$purgeInvalidationFactory protected property The 'purge.invalidation.factory' service.
PurgeBlockForm::$purgePurgers protected property The 'purge.purgers' service.
PurgeBlockForm::$purgeQueue protected property The 'purge.queue' service.
PurgeBlockForm::$queuer protected property The 'purge_ui_block_queuer' plugin.
PurgeBlockForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
PurgeBlockForm::create public static function Overrides FormBase::create
PurgeBlockForm::gatherInvalidationsData protected function Gather information for the invalidation objects to be queued/purged.
PurgeBlockForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
PurgeBlockForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
PurgeBlockForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
PurgeBlockForm::__construct final public function Construct a PurgeBlockForm object.
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.