You are here

class PathautoAdminDelete in Pathauto 8

Alias mass delete form.

Hierarchy

Expanded class hierarchy of PathautoAdminDelete

1 string reference to 'PathautoAdminDelete'
pathauto.routing.yml in ./pathauto.routing.yml
pathauto.routing.yml

File

src/Form/PathautoAdminDelete.php, line 14

Namespace

Drupal\pathauto\Form
View source
class PathautoAdminDelete extends FormBase {

  /**
   * Provides helper methods for accessing alias storage.
   *
   * @var \Drupal\pathauto\AliasStorageHelperInterface
   */
  protected $aliasStorageHelper;

  /**
   * The alias type manager.
   *
   * @var \Drupal\pathauto\AliasTypeManager
   */
  protected $aliasTypeManager;

  /**
   * Constructs a PathautoAdminDelete object.
   *
   * @param \Drupal\pathauto\AliasStorageHelperInterface $alias_storage_helper
   *   Provides helper methods for accessing alias storage.
   * @param \Drupal\pathauto\AliasTypeManager $alias_type_manager
   *   The alias type manager.
   */
  public function __construct(AliasStorageHelperInterface $alias_storage_helper, AliasTypeManager $alias_type_manager) {
    $this->aliasStorageHelper = $alias_storage_helper;
    $this->aliasTypeManager = $alias_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('pathauto.alias_storage_helper'), $container
      ->get('plugin.manager.alias_type'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['delete'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Choose aliases to delete'),
      '#tree' => TRUE,
    ];

    // First we do the "all" case.
    $total_count = $this->aliasStorageHelper
      ->countAll();
    $form['delete']['all_aliases'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('All aliases'),
      '#default_value' => FALSE,
      '#description' => $this
        ->t('Delete all aliases. Number of aliases which will be deleted: %count.', [
        '%count' => $total_count,
      ]),
    ];

    // Next, iterate over all visible alias types.
    $definitions = $this->aliasTypeManager
      ->getVisibleDefinitions();
    foreach ($definitions as $id => $definition) {

      /** @var \Drupal\pathauto\AliasTypeInterface $alias_type */
      $alias_type = $this->aliasTypeManager
        ->createInstance($id);
      $count = $this->aliasStorageHelper
        ->countBySourcePrefix($alias_type
        ->getSourcePrefix());
      $form['delete']['plugins'][$id] = [
        '#type' => 'checkbox',
        '#title' => (string) $definition['label'],
        '#default_value' => FALSE,
        '#description' => $this
          ->t('Delete aliases for all @label. Number of aliases which will be deleted: %count.', [
          '@label' => (string) $definition['label'],
          '%count' => $count,
        ]),
      ];
    }
    $form['options'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Delete options'),
      '#tree' => TRUE,
    ];

    // Provide checkbox for not deleting custom aliases.
    $form['options']['keep_custom_aliases'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Only delete automatically generated aliases'),
      '#default_value' => TRUE,
      '#description' => $this
        ->t('When checked, aliases which have been manually set are not affected by this mass-deletion.'),
    ];

    // Warn them and give a button that shows we mean business.
    $form['warning'] = [
      '#markup' => '<p>' . $this
        ->t('<strong>Note:</strong> there is no confirmation. Be sure of your action before clicking the "Delete aliases now!" button.<br />You may want to make a backup of the database and/or the path_alias and path_alias_revision tables prior to using this feature.') . '</p>',
    ];
    $form['buttons']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Delete aliases now!'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $delete_all = $form_state
      ->getValue([
      'delete',
      'all_aliases',
    ]);

    // Keeping custom aliases forces us to go the slow way to correctly check
    // the automatic/manual flag.
    if ($form_state
      ->getValue([
      'options',
      'keep_custom_aliases',
    ])) {
      $batch = [
        'title' => $this
          ->t('Bulk deleting URL aliases'),
        'operations' => [
          [
            'Drupal\\pathauto\\Form\\PathautoAdminDelete::batchStart',
            [
              $delete_all,
            ],
          ],
        ],
        'finished' => 'Drupal\\pathauto\\Form\\PathautoAdminDelete::batchFinished',
      ];
      if ($delete_all) {
        foreach (array_keys($form_state
          ->getValue([
          'delete',
          'plugins',
        ])) as $id) {
          $batch['operations'][] = [
            'Drupal\\pathauto\\Form\\PathautoAdminDelete::batchProcess',
            [
              $id,
            ],
          ];
        }
      }
      else {
        foreach (array_keys(array_filter($form_state
          ->getValue([
          'delete',
          'plugins',
        ]))) as $id) {
          $batch['operations'][] = [
            'Drupal\\pathauto\\Form\\PathautoAdminDelete::batchProcess',
            [
              $id,
            ],
          ];
        }
      }
      batch_set($batch);
    }
    elseif ($delete_all) {
      $this->aliasStorageHelper
        ->deleteAll();
      $this
        ->messenger()
        ->addMessage($this
        ->t('All of your path aliases have been deleted.'));
    }
    else {
      foreach (array_keys(array_filter($form_state
        ->getValue([
        'delete',
        'plugins',
      ]))) as $id) {
        $alias_type = $this->aliasTypeManager
          ->createInstance($id);
        $this->aliasStorageHelper
          ->deleteBySourcePrefix((string) $alias_type
          ->getSourcePrefix());
        $this
          ->messenger()
          ->addMessage($this
          ->t('All of your %label path aliases have been deleted.', [
          '%label' => $alias_type
            ->getLabel(),
        ]));
      }
    }
  }

  /**
   * Batch callback; record if aliases of all types must be deleted.
   */
  public static function batchStart($delete_all, &$context) {
    $context['results']['delete_all'] = $delete_all;
    $context['results']['deletions'] = [];
  }

  /**
   * Common batch processing callback for all operations.
   */
  public static function batchProcess($id, &$context) {

    /** @var \Drupal\pathauto\AliasTypeBatchUpdateInterface $alias_type */
    $alias_type = \Drupal::service('plugin.manager.alias_type')
      ->createInstance($id);
    $alias_type
      ->batchDelete($context);
  }

  /**
   * Batch finished callback.
   */
  public static function batchFinished($success, $results, $operations) {
    if ($success) {
      if ($results['delete_all']) {
        \Drupal::service('messenger')
          ->addMessage(t('All of your automatically generated path aliases have been deleted.'));
      }
      elseif (isset($results['deletions'])) {
        foreach (array_values($results['deletions']) as $label) {
          \Drupal::service('messenger')
            ->addMessage(t('All of your automatically generated %label path aliases have been deleted.', [
            '%label' => $label,
          ]));
        }
      }
    }
    else {
      $error_operation = reset($operations);
      \Drupal::service('messenger')
        ->addMessage(t('An error occurred while processing @operation with arguments : @args', [
        '@operation' => $error_operation[0],
        '@args' => print_r($error_operation[0]),
      ]));
    }
  }

}

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.
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.
PathautoAdminDelete::$aliasStorageHelper protected property Provides helper methods for accessing alias storage.
PathautoAdminDelete::$aliasTypeManager protected property The alias type manager.
PathautoAdminDelete::batchFinished public static function Batch finished callback.
PathautoAdminDelete::batchProcess public static function Common batch processing callback for all operations.
PathautoAdminDelete::batchStart public static function Batch callback; record if aliases of all types must be deleted.
PathautoAdminDelete::buildForm public function Form constructor. Overrides FormInterface::buildForm
PathautoAdminDelete::create public static function Instantiates a new instance of this class. Overrides FormBase::create
PathautoAdminDelete::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
PathautoAdminDelete::submitForm public function Form submission handler. Overrides FormInterface::submitForm
PathautoAdminDelete::__construct public function Constructs a PathautoAdminDelete 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.