diff --git a/drush.services.yml b/drush.services.yml new file mode 100644 index 0000000..18da029 --- /dev/null +++ b/drush.services.yml @@ -0,0 +1,5 @@ +services: + tide_webform_cleanup: + class: \Drupal\tide_webform\Commands\TideWebformSubmissionsCleanUp + tags: + - { name: drush.command } diff --git a/src/Commands/TideWebformSubmissionsCleanUp.php b/src/Commands/TideWebformSubmissionsCleanUp.php new file mode 100644 index 0000000..8df008e --- /dev/null +++ b/src/Commands/TideWebformSubmissionsCleanUp.php @@ -0,0 +1,104 @@ +writeln("Webform with ID $webform_id does not exist."); + return; + } + + if (!$webform->getElement($webform_field) || !$webform->getElement($webform_field)['#required']) { + Drush::output()->writeln("The field $webform_field is not a required field."); + return; + } + + $date_start = new DrupalDateTime($date_string); + $date_start->setTime(0, 0, 0); + $date_end = new DrupalDateTime($date_string); + $date_end->setTime(23, 59, 59); + + $query = \Drupal::entityQuery('webform_submission') + ->condition('webform_id', $webform_id) + ->condition('created', $date_start->getTimestamp(), '>=') + ->condition('created', $date_end->getTimestamp(), '<=') + ->accessCheck(FALSE); + $sids = $query->execute(); + + if (empty($sids)) { + Drush::output()->writeln("No submissions found for the specified criteria."); + return; + } + + $batch = [ + 'title' => t('Deleting submissions...'), + 'operations' => [], + 'finished' => [get_class($this), 'cleanupSubmissionsFinished'], + ]; + + foreach ($sids as $sid) { + $batch['operations'][] = [ + [get_class($this), 'deleteSubmission'], + [$sid, $webform_field], + ]; + } + + batch_set($batch); + drush_backend_batch_process(); + } + + /** + * Batch operation callback for deleting a submission. + */ + public static function deleteSubmission($sid, $webform_field, &$context) { + $submission = WebformSubmission::load($sid); + if ($submission && ($submission->getElementData($webform_field) === '' || is_null($submission->getElementData($webform_field)))) { + $submission->delete(); + $context['results']['deleted'][] = $sid; + } + else { + $context['results']['skipped'][] = $sid; + } + } + + /** + * Finished callback for the batch. + */ + public static function cleanupSubmissionsFinished($success, $results, $operations) { + if ($success) { + Drush::output()->writeln('Finished processing.'); + } + else { + Drush::output()->writeln("Finished with errors."); + } + } + +}