2013-02-14 56 views
1

我有一个包以下配置:Symfony2的TreeBuilder作为配置 - 验证对一组值

$supportedAdapters = array('curl', 'socket'); 

    $treeBuilder = new TreeBuilder(); 
    $rootNode = $treeBuilder->root('example_bundle'); 
    $rootNode 
      ->children() 
      ->scalarNode('username')->isRequired()->cannotBeEmpty()->end() 
      ->scalarNode('password')->isRequired()->cannotBeEmpty()->end() 
      ->scalarNode('adapter') 
       ->validate() 
        ->ifNotInArray($supportedAdapters) 
        ->thenInvalid('The adapter %s is not supported. Please choose one of '.json_encode($supportedAdapters)) 
       ->end() 
       ->cannotBeOverwritten() 
       ->isRequired() 
       ->cannotBeEmpty() 
      ->end() 
      // allow the use of a proxy for cURL requests 
      ->arrayNode('proxy') 
       ->children() 
        ->scalarNode('host')->isRequired()->cannotBeEmpty()->end() 
        ->scalarNode('port')->isRequired()->cannotBeEmpty()->end() 
        ->scalarNode('username')->defaultValue(null)->end() 
        ->scalarNode('password')->defaultValue(null)->end() 
       ->end() 
      ->end(); 

    return $treeBuilder; 

我们支持两种适配器:curlsocket

我们只支持使用curl请求的代理。在配置中,我想检查一下,如果设置了代理并且适配器不是curl,那么会抛出一个错误通知用户“我们只支持curl适配器与代理一起使用”。有没有办法获得一个设定值(在我们的情况下是适配器)并检查它的值并根据它进行验证?

伪代码:

IF PROXY IS SET AND ADAPTER IS NOT EQUAL TO CURL THEN: 
THROW ERROR ("We don't support the use of a proxy with the socket adapter"); 
END IF; 

我希望这是有道理的。我已经阅读了所有的文档和API文档,但是,唉,我看不到一个实现这个目标的选项。

回答

2

算出来:

$supportedAdapters = array('curl', 'socket'); 

    $treeBuilder = new TreeBuilder(); 
    $rootNode = $treeBuilder->root('example_bundle'); 
    $rootNode 
      ->validate() 
       ->ifTrue(function($v){ return isset($v['proxy']) && 'curl' !== $v['adapter'];}) 
       ->thenInvalid('Proxy support is only available to the curl adapter.') 
      ->end() 
      ->children() 
       ->scalarNode('username')->isRequired()->cannotBeEmpty()->end() 
       ->scalarNode('password')->isRequired()->cannotBeEmpty()->end() 
       ->scalarNode('adapter') 
        ->validate() 
         ->ifNotInArray($supportedAdapters) 
         ->thenInvalid('The adapter %s is not supported. Please choose one of '.json_encode($supportedAdapters)) 
        ->end() 
        ->cannotBeOverwritten() 
        ->isRequired() 
        ->cannotBeEmpty() 
       ->end() 
       // allow the use of a proxy for cURL requests 
       ->arrayNode('proxy') 
        ->children() 
         ->scalarNode('host')->isRequired()->cannotBeEmpty()->end() 
         ->scalarNode('port')->isRequired()->cannotBeEmpty()->end() 
         ->scalarNode('username')->defaultValue(null)->end() 
         ->scalarNode('password')->defaultValue(null)->end() 
        ->end() 
      ->end(); 

    return $treeBuilder; 

:-)