Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing extra, undefined options in a config array when using Symfony2's Configuration class

I'm trying to define a Configuration object. I have successfully defined an array prototype node (like security.firewalls). My prototye array has an required element but I want to allow arbitrary parameters to be added to each array if needed.

My question is, how can I allow extra, undefined elements to be added to each prototype array?

Here's my config:

acme_widget:
    handlers:
        handler_one:
            service: handler.one.service
        handler_two:
            service: handler.two.service
            extra_array:
                - Extra 1
                - Extra 2
            extra_scalar: Extra 3

Here's my class builder:

    /**
     * Generates the configuration tree.
     *
     * @return TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder;
        $rootNode = $treeBuilder->root('acme_widget');

        $rootNode
            ->children()
                ->arrayNode('handlers')
                    ->useAttributeAsKey('service')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('service')->isRequired()->end()
                            ->booleanNode('enabled')->defaultTrue()->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }

I'm getting "InvalidConfigurationException: Unrecognized options".

like image 572
mattalxndr Avatar asked Sep 22 '12 15:09

mattalxndr


1 Answers

I would just add a variable (can contain anything) node "extra":

->scalarNode('service')->isRequired()->end()
->booleanNode('enabled')->defaultTrue()->end()
->variableNode('extra')->end()

Your config would then look like:

acme_widget:
    handlers:
        handler_one:
            service: handler.one.service
        handler_two:
            service: handler.two.service
            extra:
                array:
                    - Extra 1
                    - Extra 2
                scalar: Extra 3
like image 131
AdrienBrault Avatar answered Nov 19 '22 14:11

AdrienBrault