Debian Codegraph @

vendor/symfony/console/Helper/TreeHelper.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Helper;
13
14 use Symfony\Component\Console\Output\OutputInterface;
15
16 /**
17 * The TreeHelper class provides methods to display tree-like structures.
18 *
19 * @author Simon AndrĂ© <[email protected]>
20 *
21 * @implements \RecursiveIterator<int, TreeNode>
22 */
23 final class TreeHelper implements \RecursiveIterator
24 {
25 /**
26 * @var \Iterator<int, TreeNode>
27 */
28 private \Iterator $children;
29
30 private function __construct(
31 private readonly OutputInterface $output,
32 private readonly TreeNode $node,
33 private readonly TreeStyle $style,
34 ) {
35 $this->children = new \IteratorIterator($this->node->getChildren());
36 $this->children->rewind();
37 }
38
39 public static function createTree(OutputInterface $output, string|TreeNode|null $root = null, iterable $values = [], ?TreeStyle $style = null): self
40 {
41 $node = $root instanceof TreeNode ? $root : new TreeNode($root ?? '');
42
43 return new self($output, TreeNode::fromValues($values, $node), $style ?? TreeStyle::default());
44 }
45
46 public function current(): TreeNode
47 {
48 return $this->children->current();
49 }
50
51 public function key(): int
52 {
53 return $this->children->key();
54 }
55
56 public function next(): void
57 {
58 $this->children->next();
59 }
60
61 public function rewind(): void
62 {
63 $this->children->rewind();
64 }
65
66 public function valid(): bool
67 {
68 return $this->children->valid();
69 }
70
71 public function hasChildren(): bool
72 {
73 if (null === $current = $this->current()) {
74 return false;
75 }
76
77 foreach ($current->getChildren() as $child) {
78 return true;
79 }
80
81 return false;
82 }
83
84 public function getChildren(): \RecursiveIterator
85 {
86 return new self($this->output, $this->current(), $this->style);
87 }
88
89 /**
90 * Recursively renders the tree to the output, applying the tree style.
91 */
92 public function render(): void
93 {
94 $treeIterator = new \RecursiveTreeIterator($this);
95
96 $this->style->applyPrefixes($treeIterator);
97
98 $this->output->writeln($this->node->getValue());
99
100 $visited = new \SplObjectStorage();
101 foreach ($treeIterator as $node) {
102 $currentNode = $node instanceof TreeNode ? $node : $treeIterator->getInnerIterator()->current();
103 if (isset($visited[$currentNode])) {
104 throw new \LogicException(\sprintf('Cycle detected at node: "%s".', $currentNode->getValue()));
105 }
106 $visited[$currentNode] = true;
107
108 $this->output->writeln($node);
109 }
110 }
111 }