Skip to content

[Configuration] Use of source keys as result keys for prototype nodes #12304

Closed
@lividgreen

Description

@lividgreen

Here is the code example when source keys are ignored in processed configuration:

<?php
$processor = new \Symfony\Component\Config\Definition\Processor();

$treeBuilder = new \Symfony\Component\Config\Definition\Builder\TreeBuilder();
$root = $treeBuilder->root('my_config');
$root->prototype('scalar')->end();

$result = $processor->process($treeBuilder->buildTree(), array(array('one' => '1', 'two' => '2')));
var_dump($result); // keys "one" and "two" are ignored

Result:

array(2) {
  [0] =>
  string(1) "1"
  [1] =>
  string(1) "2"
}

Here is another example that adds source keys to the result:

<?php
$processor = new \Symfony\Component\Config\Definition\Processor();

$treeBuilder = new \Symfony\Component\Config\Definition\Builder\TreeBuilder();
$root = $treeBuilder->root('my_config');
$root
    ->useAttributeAsKey('whatever') // magic
    ->prototype('scalar')
    ->end();

$result = $processor->process($treeBuilder->buildTree(), array(array('one' => '1', 'two' => '2')));
var_dump($result);

Result:

array(2) {
  'one' =>
  string(1) "1"
  'two' =>
  string(1) "2"
}

This also affects merging:

<?php
$processor = new \Symfony\Component\Config\Definition\Processor();

$treeBuilder = new \Symfony\Component\Config\Definition\Builder\TreeBuilder();
$root = $treeBuilder->root('my_config');
$root
    ->useAttributeAsKey('the_key') // magic
    ->prototype('array')
        ->children()
            ->scalarNode('the_key')->end()
            ->scalarNode('the_value')->end()
        ->end()
    ->end();

$config1 = array(
    array('the_key' => 'key1', 'the_value' => 'value1'),
    array('the_key' => 'key2', 'the_value' => 'value2'),
);
$config2 = array(
    'key1' => array('the_value' => 'value3'), // 'the_key' is not present
);

$result = $processor->process($treeBuilder->buildTree(), array($config1, $config2));
var_dump($result);

Result:

array(2) {
  'key1' =>
  array(1) {
    'the_value' =>
    string(6) "value3"
  }
  'key2' =>
  array(1) {
    'the_value' =>
    string(6) "value2"
  }
}

This "feature" is not documented and looks like a magic. I wish there was documented way to preserve keys of prototyped values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions