You are here

function field_encrypt_encryption_profile_predelete in Field Encryption 3.0.x

Implements hook_ENTITY_TYPE_predelete().

File

./field_encrypt.module, line 251
Contains module hooks for field_encrypt.

Code

function field_encrypt_encryption_profile_predelete(EncryptionProfile $profile) {

  // Prevent encryption profiles from being deleted if they are in use.
  if ($profile
    ->id() === \Drupal::config('field_encrypt.settings')
    ->get('encryption_profile')) {
    throw new \RuntimeException(sprintf('Cannot delete %s encryption profile because it is the default for the field_encrypt module', $profile
      ->id()));
  }
  $entity_types = \Drupal::state()
    ->get('field_encrypt.entity_types', []);
  $entity_type_manager = \Drupal::entityTypeManager();
  foreach ($entity_types as $entity_type_id) {
    if (!$entity_type_manager
      ->hasDefinition($entity_type_id)) {
      continue;
    }
    $query = $entity_type_manager
      ->getStorage($entity_type_id)
      ->getQuery();
    $query
      ->condition(ProcessEntities::ENCRYPTED_FIELD_STORAGE_NAME . '.encryption_profile', $profile
      ->id());
    if ($entity_type_manager
      ->getDefinition($entity_type_id)
      ->isRevisionable()) {
      $query
        ->allRevisions();
    }
    if ($query
      ->count()
      ->execute() > 0) {
      throw new \RuntimeException(sprintf('Cannot delete %s encryption profile because it is in-use by %s entities', $profile
        ->id(), $entity_type_id));
    }
  }
}