Updates config with values set on Drupal 7.x.
Provides a generalised method to migrate variables from Drupal 7 to Drupal 8's configuration management system.
string $config_name: The configuration object name to retrieve.
array $variable_map: An associative array that maps old variables names to new configuration object keys; e.g.:
array(
'old_variable' => 'new_config.sub_key',
);
This would migrate the value contained in variable name 'old_variable' into the data key 'new_config.sub_key' of the configuration object $config_name.
function update_variables_to_config($config_name, array $variable_map) {
// Build the new configuration object.
// This potentially loads an existing configuration object, in case another
// update function migrated configuration values into $config_name already.
$config = config($config_name);
$original_data = $config
->get();
// Extract the module namespace/owner from the configuration object name.
$module = strtok($config_name, '.');
// Load and set default configuration values.
$file = new FileStorage(drupal_get_path('module', $module) . '/config');
if (!$file
->exists($config_name)) {
throw new ConfigException("Default configuration file {$config_name} for {$module} extension not found but is required to exist.");
}
$default_data = $file
->read($config_name);
// Apply the default values.
$config
->setData($default_data);
// Merge any possibly existing original data into default values.
// Only relevant when being called repetitively on the same config object.
if (!empty($original_data)) {
$config
->merge($original_data);
}
// Fetch existing variables.
$variables = db_query('SELECT name, value FROM {variable} WHERE name IN (:variables)', array(
':variables' => array_keys($variable_map),
))
->fetchAllKeyed();
// Set configuration values according to the provided variable mapping.
foreach ($variable_map as $variable_name => $config_key) {
// This function migrates variables regardless of their value, including
// NULL values. Any possibly required customizations need to be performed
// manually, either via variable_set() before calling this function or via
// config() after calling this function.
if (isset($variables[$variable_name])) {
$value = unserialize($variables[$variable_name]);
$config
->set($config_key, $value);
}
}
// Save the configuration object.
$config
->save();
// Delete the migrated variables.
db_delete('variable')
->condition('name', array_keys($variable_map), 'IN')
->execute();
}