You are here

public function WebformSubmissionStorageTest::testPurge in Webform 8.5

Same name and namespace in other branches
  1. 6.x tests/src/Kernel/WebformSubmissionStorageTest.php \Drupal\Tests\webform\Kernel\WebformSubmissionStorageTest::testPurge()

Test purging of the webform submissions.

@dataProvider providerPurge

File

tests/src/Kernel/WebformSubmissionStorageTest.php, line 59

Class

WebformSubmissionStorageTest
Tests webform submission storage.

Namespace

Drupal\Tests\webform\Kernel

Code

public function testPurge($webform_purging, $webform_submissions_definition, $purged) {
  $request_time = \Drupal::time()
    ->getRequestTime();
  $days_to_seconds = 60 * 60 * 24;
  $purge_days = 10;
  $purge_amount = 2;
  $webform = Webform::create([
    'id' => $this
      ->randomMachineName(),
  ]);
  $webform
    ->setSetting('purge', $webform_purging);
  $webform
    ->setSetting('purge_days', $purge_days);
  $webform
    ->save();
  $webform_no_purging = Webform::create([
    'id' => $this
      ->randomMachineName(),
  ]);
  $webform_no_purging
    ->setSetting('purge', WebformSubmissionStorageInterface::PURGE_NONE);
  $webform_no_purging
    ->save();
  foreach ($webform_submissions_definition as $definition) {
    foreach ([
      $webform,
      $webform_no_purging,
    ] as $v) {
      $webform_submission = WebformSubmission::create([
        'webform_id' => $v
          ->id(),
      ]);
      $webform_submission->in_draft = $definition[0];
      $webform_submission
        ->setCreatedTime($definition[1] ? $request_time - ($purge_days + 1) * $days_to_seconds : $request_time);
      $webform_submission
        ->save();
    }
  }
  \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->purge($purge_amount);

  // Make sure nothing has been purged in the webform where purging is
  // disabled.
  $query = \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->getQuery();
  $query
    ->accessCheck(FALSE);
  $query
    ->condition('webform_id', $webform_no_purging
    ->id());
  $result = $query
    ->execute();
  $this
    ->assertEquals(count($webform_submissions_definition), count($result), 'No purging is executed when webform is not set up to purge.');
  $query = \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->getQuery();
  $query
    ->accessCheck(FALSE);
  $query
    ->condition('webform_id', $webform
    ->id());
  $result = [];
  foreach (\Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->loadMultiple($query
    ->execute()) as $submission) {
    $result[$submission
      ->serial()] = $submission;
  }
  foreach ($purged as $sequence_id) {
    $this
      ->assertArrayNotHasKey($sequence_id, $result, 'Webform submission with sequence ' . $sequence_id . ' is purged.');
  }
  $this
    ->assertEquals(count($webform_submissions_definition) - count($purged), count($result), 'Remaining webform submissions are not purged.');
}