Skip to content

Instantly share code, notes, and snippets.

@tobalsan
Last active August 29, 2015 14:04
Show Gist options
  • Save tobalsan/ce210d7b2e7dd7c704e7 to your computer and use it in GitHub Desktop.
Save tobalsan/ce210d7b2e7dd7c704e7 to your computer and use it in GitHub Desktop.
Symfony2: Allow nested parameters in configuration YAML
// app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
# various imports
- { resource: acmehello.yml }
// app/config/acmehello.yml
acme_hello:
param:
one: foo
two: bar
other:
three: baz
soon: "my value"
<?php
// src/Acme/HelloBundle/DependencyInjection/Configuration.php
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('acme_hello');
return $treeBuilder;
}
}
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
class AcmeHelloExtension extends Extension
{
/**
* Default function that loads values from yaml config files
*/
public function load(array $configs, ContainerBuilder $container)
{
foreach ($configs as $subconfig) {
$config = $this->unNest($subconfig, null, null, 2);
foreach ($config as $key => $value) {
$container->setParameter($key, $value);
}
}
// $configuration = new Configuration();
// $config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('config.yml');
}
/**
* The function that parses the array to flatten it into a one level depth array
*
* @param $elem The array containing the config values
* @param $path Links each array key to make a condensed key. e.g: $subconfig[param][info][test] becomes $subconfig[param.info.test]
* @param $result Each array passed recursively to go down and get the final values
* @param $maxDepth The maxmium depth to go through the conig array. Once reached, all sub values are returned as array instead of scalar. Useful when you want to store arrays as parameters
*/
protected function unNest($elem, $path = null, $result = null, $maxDepth = 10)
{
if($result === null){
$result = array();
}
if(is_array($elem) AND $maxDepth){
foreach ($elem as $key => $value) {
$newPath = $path ? $path . '.' . $key : $key;
$result = $this->unNest($value, $newPath, $result, $maxDepth - 1);
}
} else {
$result[$path] = $elem;
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment