Skip to content

Instantly share code, notes, and snippets.

@ikorgik
Last active August 16, 2018 13:42
Show Gist options
  • Save ikorgik/2116de3b7eddd7b8f2a15db9274d2933 to your computer and use it in GitHub Desktop.
Save ikorgik/2116de3b7eddd7b8f2a15db9274d2933 to your computer and use it in GitHub Desktop.
Import config programmatically in Drupal 8
<?php
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Config\StorageComparer;
use Drupal\Core\Config\ConfigException;
/**
* Imports configurations programmaticaly in Drupal 8.
*
* Makes the same action as `drush cim -y`.
* Based on the code from config.drush.inc:drush_config_import method.
*/
function configuration_import() {
$storage_comparer = new StorageComparer(
\Drupal::service('config.storage.sync'),
\Drupal::service('config.storage'),
\Drupal::service('config.manager')
);
$config_importer = new ConfigImporter(
$storage_comparer,
\Drupal::service('event_dispatcher'),
\Drupal::service('config.manager'),
\Drupal::lock(),
\Drupal::service('config.typed'),
\Drupal::moduleHandler(),
\Drupal::service('module_installer'),
\Drupal::service('theme_handler'),
\Drupal::service('string_translation')
);
// Make sure configuration has changes.
if ($storage_comparer->createChangelist()->hasChanges()) {
// Import configurations.
$config_importer->import();
// There is an error during config import.
if ($config_importer->getErrors()) {
throw new ConfigException('Errors occurred during import');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment