2015-03-13 84 views
3

我很抱歉地說我找不到一種方法來將一個默認值添加到「symfony/config」:「2.6.4」ConfigurationInterface!symfony/config arrayNode原型addDefaultsIfNotSet

什麼希望是這種類型的配置中:

X: 
    Y: 
     - test 
     - testing 

隨着默認爲:

X: 
    Y: 
     - test 

通過 「默認」 我的意思是:如果Y config分支未設置讀取配置文件, $ process-> processConfiguration應該添加它(如果我刪除 - >原型...)

這是我的代碼:

class Definition implements ConfigurationInterface 
{ 
    /** 
    * {@inheritdoc} 
    */ 
    public function getConfigTreeBuilder() 
    { 
     $treeBuilder = new TreeBuilder(); 
     $rootNode = $treeBuilder->root("X"); 
     $rootNode 
      ->children() 
       ->arrayNode("Y") 
        ->addDefaultsIfNotSet() 
        ->info("Multiple values can be used") 
        ->cannotBeEmpty() 
        ->addDefaultIfNotSet() 
        ->defaultValue(array("test")) 
        ->prototype("scalar") 
         ->validate() 
         ->ifNotInArray(array("test", "testing")) 
          ->thenInvalid("Invalid value %s") 
         ->end() 
        ->end() 
       ->end() 
      ->end() 
     ; 

     return $treeBuilder; 
    } 
} 

當然,我讀了這個問題Using the Symfony2 configuration class, how do I define an array node whose children don't have keys?

我當前的代碼實現這種方式,你可以讀,但它不工作,我的代碼拋出:

[Symfony\Component\Config\Definition\Exception\InvalidDefinitionException] 
    ->addDefaultsIfNotSet() is not applicable to prototype nodes at path "X.Y" 

回答

2

僅供參考,我終於得到了它通過一個變量節點,就在我用頭撞牆之前一分鐘;)

class Definition implements ConfigurationInterface 
{ 
    /** 
    * {@inheritdoc} 
    */ 
    public function getConfigTreeBuilder() 
    { 
     $treeBuilder = new TreeBuilder(); 
     $rootNode = $treeBuilder->root("X"); 
     $rootNode 
      ->children() 
       ->variableNode("Y") 
        ->info("Multiple values can be used") 
        ->cannotBeEmpty() 
        ->defaultValue(array("test")) 
        ->validate() 
         ->always(function ($values) { 
          foreach ((array) $values as $value) { 
           if (! in_array($value, array("test", "testing"))) { 
            throw new \Symfony\Component\Config\Definition\Exception\InvalidTypeException("Invalid value ".$value); 
           } 
          } 
          return (array) $values; 
         }) 
        ->end() 
       ->end() 
      ->end() 
     ; 

     return $treeBuilder; 
    } 
} 

似乎沒有辦法用arrayNode做到這一點!但是,如果一個發現如何,請不要猶豫地回答,我會很高興地接受使用arrayNode答案,因爲集成驗證可能是比我好......

0

什麼:

<?php 
    $rootNode 
     ->children() 
      ->arrayNode("Y") 
       ->defaultValue(array("test")) 
       ->prototype("scalar") 
        ->validate() 
        ->ifNotInArray(array("test", "testing")) 
         ->thenInvalid("Invalid value %s") 
        ->end() 
       ->end() 
      ->end() 
     ->end() 
    ; 

另一個問題是,爲什麼不重構配置。你想要一份testtest, testingtesting的清單。你爲什麼不對其進行配置,如:

X: 
    Y: 
    test: true 
    testing: false 

隨着X.Y.test = true默認和X.Y.testing = false?那麼你的Configuration會很容易。