2013-02-14 63 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; 

:-)