2012-12-11 49 views
2

我正在使用Symfony2的樹生成器,我看到這裏有一些基本的驗證規則:http://symfony.com/doc/current/components/config/definition.html#validation-rules在Symfony2配置TreeBuilder中使用正則表達式驗證?

有沒有辦法通過正則表達式驗證?

以下是我目前正在做的事情,但我不確定這是否是「最佳實踐」。我想要驗證的配置項是root_node

config.yml

my_bundle: 
    root_node: /some/path # this one is valid 

的configuration.php

$treeBuilder = new TreeBuilder(); 
$rootNode = $treeBuilder->root('my_bundle'); 

$rootNode 
    ->children() 
     ->scalarNode('root_node') 
      ->end() 
     ->end() 
    ->end(); 

return $treeBuilder; 

MyBundleExtension.php

$nodePattern = '#/\w+(/w+)*#'; 
if (! preg_match($nodePattern, $config['root_node'])) { 
    throw new \Exception("root_node is not valid: must match the pattern: $nodePattern"); 
} 

那麼,什麼我真的後是TreeBuilder作爲方法:

->validate()->ifNotMatchesRegex()->thenInvalid() 

,或做不到這一點,最好的辦法強制執行我的驗證規則。

回答

5

您可以做的是使用ifTrue方法與您的自定義功能。這樣的事情:

$rootNode 
    ->children() 
     ->scalarNode('root_node') 
      ->validate() 
      ->ifTrue(function ($s) { 
       return preg_match('#/\w+(/\w+)*#', $s) !== 1; 
      }) 
       ->thenInvalid('Invalid path') 
      ->end() 
     ->end() 
    ->end(); 

請注意我對你的正則表達式的輕微修改。

+0

謝謝,不能希望有更好的答案。同樣在正則表達式中,我錯過了^和$標記,因此最終版本是:#^/\ w +(/ \ w +)* $# – fazy

+0

如果您想使用自定義無效/錯誤消息,知道你可以在消息中包含潛在的錯誤值,如'無效路徑:%s' – Jan