You are here

public function BulkDeleteTest::testPurgeField in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/field/tests/src/Kernel/BulkDeleteTest.php \Drupal\Tests\field\Kernel\BulkDeleteTest::testPurgeField()

Verify that field data items and fields are purged when a field storage is deleted.

File

core/modules/field/tests/src/Kernel/BulkDeleteTest.php, line 313

Class

BulkDeleteTest
Bulk delete storages and fields, and clean up afterwards.

Namespace

Drupal\Tests\field\Kernel

Code

public function testPurgeField() {

  // Start recording hook invocations.
  field_test_memorize();
  $bundle = reset($this->bundles);
  $field_storage = reset($this->fieldStorages);
  $field_name = $field_storage
    ->getName();

  // Delete the field.
  $field = FieldConfig::loadByName($this->entityTypeId, $bundle, $field_name);
  $field
    ->delete();

  // No field hooks were called.
  $mem = field_test_memorize();
  $this
    ->assertCount(0, $mem, 'No field hooks were called');
  $batch_size = 2;
  for ($count = 8; $count >= 0; $count -= $batch_size) {

    // Purge two entities.
    field_purge_batch($batch_size);

    // There are $count deleted entities left.
    $found = \Drupal::entityQuery('entity_test')
      ->condition('type', $bundle)
      ->condition($field_name . '.deleted', 1)
      ->execute();
    $this
      ->assertEqual(count($found), $count, 'Correct number of entities found after purging 2');
  }

  // Check hooks invocations.
  // FieldItemInterface::delete() should have been called once for each entity in the
  // bundle.
  $actual_hooks = field_test_memorize();
  $hooks = [];
  $hooks['field_test_field_delete'] = $this->entitiesByBundles[$bundle];
  $this
    ->checkHooksInvocations($hooks, $actual_hooks);

  // The field still exists, deleted.
  $fields = \Drupal::entityTypeManager()
    ->getStorage('field_config')
    ->loadByProperties([
    'field_storage_uuid' => $field_storage
      ->uuid(),
    'deleted' => TRUE,
    'include_deleted' => TRUE,
  ]);
  $this
    ->assertCount(1, $fields, 'There is one deleted field');

  // Purge the field.
  field_purge_batch($batch_size);

  // The field is gone.
  $fields = \Drupal::entityTypeManager()
    ->getStorage('field_config')
    ->loadByProperties([
    'field_storage_uuid' => $field_storage
      ->uuid(),
    'deleted' => TRUE,
    'include_deleted' => TRUE,
  ]);
  $this
    ->assertCount(0, $fields, 'The field is gone');

  // The field storage still exists, not deleted, because it has a second
  // field.
  $storages = \Drupal::entityTypeManager()
    ->getStorage('field_storage_config')
    ->loadByProperties([
    'uuid' => $field_storage
      ->uuid(),
    'include_deleted' => TRUE,
  ]);
  $this
    ->assertTrue(isset($storages[$field_storage
    ->uuid()]), 'The field storage exists and is not deleted');
}