Skip to content
Advertisement

How to parse simple key => value pairs using symfony config component

I am trying to integrate Symfony config component and have some trouble getting it to parse required YAML format. I can’t find a way for the Config component to accept simple key => value pairs from the YAML file.

My current tree builder for the “limits” section:

    $treeBuilder = new TreeBuilder('limits');

    $node = $treeBuilder->getRootNode();

    foreach ($keys as $key) {
        $node
            ->isRequired()
            ->children()
                ->arrayNode('comment')
                    ->isRequired()
                    ->requiresAtLeastOneElement()
                    ->useAttributeAsKey('name', false)
                    ->prototype('array')
                        ->canBeDisabled()
                        ->treatNullLike(['enabled' => false])
                        ->children()
                            ->integerNode('duration')->end()
                            ->integerNode('limit')->end()
                            ->arrayNode('thresholds')
                                ->useAttributeAsKey('name', false)                      
                                ->prototype('array')
                                    ->children()
                                        ->scalarNode('name')->end()
                                        ->integerNode('value')->end()
                                    ->end()
                                ->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end();
    }
    return $node;

The yaml tree that I am already able to parse is as follows:

limits:
    comment:
        per_hour:
            duration: 3600
            limit: 100
            thresholds:
                key1:
                    value: 50
                key2:
                    value: 60
                ...

And I want to modify it so I can write configuration like this:

limits:
    comment:
        per_hour:
            duration: 3600
            limit: 100
            thresholds:
                key1: 50
                key2: 60
                ...

Any idea how I could modify the tree builder to get the required format?

thanks!

Advertisement

Answer

starting from your code, changing your thresholds definition to this, should do what you expect :

    ->arrayNode('thresholds')
        ->useAttributeAsKey('name', false)
        ->prototype('integer')->end()
    ->end()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement