Symfony3 configuration component validation

113 views Asked by At

Community I need your help. I have config file:

payments:
    methods:
        paypal:
           enabled: false
           allowed_countries:
              - <country>
              - ...
        credit_card:
           disallowed_countries:
              - <country>
              - ...

How can I validate using the TreeBuilder if arrayNode is containing only one of 2 allowed arrays: allowed_countries or disallowed_countries and throw exception if there is two arrays together? Symfony version 3.2

1

There are 1 answers

0
Pieter On BEST ANSWER

You can add more complex validation to your configuration tree builder by using validation rules with the ExprBuilder.

This would look something like:

$rootNode
    ->isRequired()
    ->validate()
        ->ifTrue(function($options) {
            return !($options['allowed_countries'] xor $options['disallowed_countries']);
        })
        ->thenInvalid('Either define allowed_countries or disallowed_countries, not both')
        ->end()
    ->children()
        ->arrayNode('allowed_countries')
            ->scalarPrototype()->end()
        ->end()
        ->arrayNode('disallowed_countries')
            ->scalarPrototype()->end()
        ->end()
    ->end();