Skip to content

Instantly share code, notes, and snippets.

@megclaypool
Last active May 20, 2023 06:06
Show Gist options
  • Save megclaypool/2de08491781045470f18e31b75b5fb10 to your computer and use it in GitHub Desktop.
Save megclaypool/2de08491781045470f18e31b75b5fb10 to your computer and use it in GitHub Desktop.
[Drupal Import and delete config files programmatically (PHP)]
/**
 * Helper function / example code to check
 * if the given configuration (by name)
 * exists in active configuration.
 * @param string $configName
 *   The id of the configuration to check.
 *
 * @return boolean
 *
 */
function isInActiveConfig($configId = 'core.extension'){
  $activeConfigFactory = \Drupal::service('config.factory');
  // The config factory always returns an ImmutableConfig object
  // but if doesn't exist in configuration yet, ->isNew() is true.
  $existsInActiveConfig = !$activeConfigFactory->get($configId)->isNew();
  return $existsInActiveConfig;
}

function getConfigs() {
  return [
    "field.storage.block_content.field_social_sharing_options",
    "field.field.block_content.social_sharing.field_social_sharing_options",
    "taxonomy.vocabulary.social_sharing_options",
    'field.field.taxonomy_term.social_sharing_options.field_sharing_slug',
    "block_content.type.social_sharing",
    "core.entity_form_display.taxonomy_term.social_sharing_options.default",
    "core.entity_view_display.block_content.social_sharing.default",
    "core.entity_view_display.taxonomy_term.social_sharing_options.slug",
    "core.entity_view_mode.taxonomy_term.slug",
    "block.block.socialsharing",
  ];
}


/**
 * Implements hook_install().
 */
function radicati_social_install() {
  // Manually import the config files
  $module_path = \Drupal::service('module_handler')->getModule('radicati_social')->getPath();
  $config_path = $module_path . '/config/manual';
  $source = new FileStorage($config_path);
  $config_storage = \Drupal::service('config.storage');
  $social_sharing_configs = getConfigs();
  
  foreach ($social_sharing_configs as $config) {
    if (!isInActiveConfig($config)) {
      $config_storage->write($config, $source->read($config));
    }
  }
}


/**
 * Implements hook_uninstall().
 */
function radicati_social_uninstall() {
  // Delete the configs on uninstall
  $social_sharing_configs = getConfigs();

  foreach ($social_sharing_configs as $config) {
    if (isInActiveConfig($config)) {
      \Drupal::configFactory()->getEditable($config)->delete();
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment