You are here

function drush_yamlform_purge in YAML Form 8

Implements drush_hook_COMMAND().

File

drush/yamlform.drush.inc, line 282
YAML Form module drush commands.

Code

function drush_yamlform_purge($yamlform_id = NULL) {
  if (drush_get_option('all')) {
    $yamlform_id = 'all';
  }
  if (!$yamlform_id) {
    $yamlforms = array_keys(YamlForm::loadMultiple());
    $choices = array_combine($yamlforms, $yamlforms);
    $choices = array_merge([
      'all' => 'all',
    ], $choices);
    $yamlform_id = drush_choice($choices, dt("Choose a form to purge submissions from."));
    if ($yamlform_id === FALSE) {
      return drush_user_abort();
    }
  }

  // Set the form.
  $yamlform = $yamlform_id == 'all' ? NULL : YamlForm::load($yamlform_id);

  /** @var \Drupal\yamlform\YamlFormSubmissionStorageInterface $submission_storage */
  $submission_storage = \Drupal::entityTypeManager()
    ->getStorage('yamlform_submission');

  /** @var \Drupal\yamlform\YamlFormRequestInterface $request_handler */
  $request_handler = \Drupal::service('yamlform.request');

  // Make sure there are submissions that need to be deleted.
  if (!$submission_storage
    ->getTotal($yamlform)) {
    return drush_set_error(dt('There are no submissions that need to be deleted.'));
  }
  if (!$yamlform) {
    $submission_total = \Drupal::entityQuery('yamlform_submission')
      ->count()
      ->execute();
    $form_total = \Drupal::entityQuery('yamlform')
      ->count()
      ->execute();
    $t_args = [
      '@submission_total' => $submission_total,
      '@submissions' => \Drupal::translation()
        ->formatPlural($submission_total, t('submission'), t('submissions')),
      '@form_total' => $form_total,
      '@forms' => \Drupal::translation()
        ->formatPlural($form_total, t('form'), t('forms')),
    ];
    if (!drush_confirm(dt('Are you sure you want to delete @submission_total @submissions in @form_total @forms?', $t_args))) {
      return drush_user_abort();
    }
    $form = new YamlFormResultsClearForm($submission_storage, $request_handler);
    $form
      ->batchSet();
    drush_backend_batch_process();
  }
  else {

    // Set source entity.
    $entity_type = drush_get_option('entity-type');
    $entity_id = drush_get_option('entity-id');
    $source_entity = $entity_type && $entity_id ? \Drupal::entityTypeManager()
      ->getStorage($entity_type)
      ->load($entity_id) : NULL;
    $t_args = [
      '@title' => $source_entity ? $source_entity
        ->label() : $yamlform
        ->label(),
    ];
    if (!drush_confirm(dt("Are you sure you want to delete all submissions from '@title' form?", $t_args))) {
      return drush_user_abort();
    }
    $form = new YamlFormSubmissionsPurgeForm($submission_storage, $request_handler);
    $form
      ->batchSet($yamlform, $source_entity);
    drush_backend_batch_process();
  }
}