TreeBuilder.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Config\Definition\Builder;
  11. use Symfony\Component\Config\Definition\NodeInterface;
  12. /**
  13. * This is the entry class for building a config tree.
  14. *
  15. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  16. */
  17. class TreeBuilder implements NodeParentInterface
  18. {
  19. protected $tree;
  20. protected $root;
  21. protected $builder;
  22. /**
  23. * Creates the root node.
  24. *
  25. * @param string $name The name of the root node
  26. * @param string $type The type of the root node
  27. * @param NodeBuilder $builder A custom node builder instance
  28. *
  29. * @return ArrayNodeDefinition|NodeDefinition The root node (as an ArrayNodeDefinition when the type is 'array')
  30. *
  31. * @throws \RuntimeException When the node type is not supported
  32. */
  33. public function root($name, $type = 'array', NodeBuilder $builder = null)
  34. {
  35. $builder = $builder ?: new NodeBuilder();
  36. return $this->root = $builder->node($name, $type)->setParent($this);
  37. }
  38. /**
  39. * Builds the tree.
  40. *
  41. * @return NodeInterface
  42. *
  43. * @throws \RuntimeException
  44. */
  45. public function buildTree()
  46. {
  47. if (null === $this->root) {
  48. throw new \RuntimeException('The configuration tree has no root node.');
  49. }
  50. if (null !== $this->tree) {
  51. return $this->tree;
  52. }
  53. return $this->tree = $this->root->getNode(true);
  54. }
  55. }