Last active
September 17, 2022 15:58
-
-
Save xphere/c7cd079dd4775410bad6 to your computer and use it in GitHub Desktop.
Recursive symfony/configuration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; | |
use Symfony\Component\Config\Definition\Builder\TreeBuilder; | |
use Symfony\Component\Config\Definition\ConfigurationInterface; | |
/** | |
* Helper function to create recursive nodes | |
*/ | |
function recursiveNode(string $name, callable $callback) | |
{ | |
$builder = new TreeBuilder(); | |
$root = $builder->root($name, 'variable'); | |
$root->defaultValue([]); | |
$root | |
->beforeNormalization() | |
->ifTrue(function ($v) { return !is_array($v); }) | |
->thenInvalid("The {$name} element must be an array.") | |
; | |
$root | |
->beforeNormalization() | |
->always(function (iterable $children) use ($builder, $callback) { | |
$config = []; | |
foreach ($children as $name => $child) { | |
$node = $builder->root($name); | |
$callback($node, $callback); | |
$config[$name] = $node->getNode(true)->finalize($child); | |
} | |
return $config; | |
}) | |
; | |
return $root; | |
} | |
/** | |
* Usage of recursiveNode | |
* This allows for configuration like: | |
* | |
* routing_bundle: | |
* routes: | |
* - name: route_1 | |
* url: url_1 | |
* children: | |
* - name: route_2 | |
* url: url_2 | |
* - name: route_3 | |
* url: url_3 | |
* children: | |
* - name: route_4 | |
* - url: url_4 | |
* - name: route_5 | |
* url: url_5 | |
*/ | |
class Configuration implements ConfigurationInterface | |
{ | |
public function getConfigTreeBuilder() | |
{ | |
$tree = new TreeBuilder(); | |
$root = $tree->root('my_routing_bundle'); | |
$root | |
->children() | |
->append( | |
recursiveNode('routes', function ($node, $recursive) { | |
return $this->routes($node, $recursive); | |
}) | |
) | |
->end() | |
; | |
return $tree; | |
} | |
private function routes(ArrayNodeDefinition $node, callable $recursive) | |
{ | |
$node | |
->addDefaultsIfNotSet() | |
->children() | |
->scalarNode('description')->end() | |
->scalarNode('name') | |
->isRequired() | |
->cannotBeEmpty() | |
->end() | |
->scalarNode('url') | |
->defaultNull() | |
->end() | |
->append(recursiveNode('children', $recursive)) | |
; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@aesislabs I solve!