Skip to content

Instantly share code, notes, and snippets.

@lolandese
Last active January 14, 2022 13:36
Show Gist options
  • Select an option

  • Save lolandese/eb0e2392264aca7d736dd712e432410e to your computer and use it in GitHub Desktop.

Select an option

Save lolandese/eb0e2392264aca7d736dd712e432410e to your computer and use it in GitHub Desktop.
Convert a Drupal YAML configuration file to an array as a working PHP code snippet to write its values to the database. This is code to generate code. Short URL: https://git.io/fjjDu
<?php
/**
* @file
* Convert a YAML file to PHP code to write its values to the database.
*/
use Drupal\Component\Serialization\Yaml;
// Replace 'filter.format.full_html' with any other existing configuration
// object. The configuration YAML file must exist. Export the configuration
// first if that is not the case.
$input = 'filter.format.full_html';
// Parse the YAML file and convert it to a PHP array.
$yamlDecoded = Yaml::decode(file_get_contents(dirname(\Drupal::root()) . '/config/' . CONFIG_SYNC_DIRECTORY . '/' . $input . '.yml'));
// Remove the 'UUID' and '_core'. Not needed in the generated code.
unset($yamlDecoded['uuid']);
unset($yamlDecoded['_core']);
// Create a variable name based on the configuration object name.
$dynamic_var = '$' . str_replace('.', '_', $input);
// Create a parsable string representation of the YAML file.
$output = print_r(var_export($yamlDecoded, TRUE), TRUE);
// Sanitize the output according to the Drupal coding standard.
$target = [
'/array \(/',
'/\)/',
'/true/',
'/false/',
'/=>[ \t]+' . PHP_EOL . '[ \t]+\[' . PHP_EOL . '[ \t]+\],/',
'/=>[ \t]+' . PHP_EOL . '/',
];
$replacement = [
'[',
']',
'TRUE',
'FALSE',
'=> [],',
'=>' . PHP_EOL,
];
$output = preg_replace($target, $replacement, $output);
// Generate the PHP code snippet.
print('<h2>PHP code to copy and paste</h2>');
print('<pre>' . highlight_string("<?php
/**
* @file
* Set a complete configuration object in the database.
*/
// Still to export to the configuration YAML file (drush cex).
// Code generated with https://git.io/fjjDu (leave for future reference).
$dynamic_var = $output;
\Drupal::configFactory()->getEditable('$input')->setData($dynamic_var)
->save();
", TRUE) . '</pre>');
@lolandese
Copy link
Author

lolandese commented Sep 7, 2019

To convert a Drupal YAML snippet to a working PHP code snippet, go to https://git.io/Jem8t.

This can also be just a part of a YAML, either from a file or from the database suggested as export at admin/config/development/configuration/single/export.

@todo
Add error handling, messaging and logging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment