Debian Codegraph @

vendor/symfony/console/Helper/TreeNode.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 /**
15 * @implements \IteratorAggregate<TreeNode>
16 *
17 * @author Simon AndrĂ© <[email protected]>
18 */
19 final class TreeNode implements \Countable, \IteratorAggregate
20 {
21 /**
22 * @var array<TreeNode|callable(): \Generator>
23 */
24 private array $children = [];
25
26 public function __construct(
27 private readonly string $value = '',
28 iterable $children = [],
29 ) {
30 foreach ($children as $child) {
31 $this->addChild($child);
32 }
33 }
34
35 public static function fromValues(iterable $nodes, ?self $node = null): self
36 {
37 $node ??= new self();
38 foreach ($nodes as $key => $value) {
39 if (is_iterable($value)) {
40 $child = new self($key);
41 self::fromValues($value, $child);
42 $node->addChild($child);
43 } elseif ($value instanceof self) {
44 $node->addChild($value);
45 } else {
46 $node->addChild(new self($value));
47 }
48 }
49
50 return $node;
51 }
52
53 public function getValue(): string
54 {
55 return $this->value;
56 }
57
58 public function addChild(self|string|callable $node): self
59 {
60 if (\is_string($node)) {
61 $node = new self($node);
62 }
63
64 $this->children[] = $node;
65
66 return $this;
67 }
68
69 /**
70 * @return \Traversable<int, TreeNode>
71 */
72 public function getChildren(): \Traversable
73 {
74 foreach ($this->children as $child) {
75 if (\is_callable($child)) {
76 yield from $child();
77 } elseif ($child instanceof self) {
78 yield $child;
79 }
80 }
81 }
82
83 /**
84 * @return \Traversable<int, TreeNode>
85 */
86 public function getIterator(): \Traversable
87 {
88 return $this->getChildren();
89 }
90
91 public function count(): int
92 {
93 $count = 0;
94 foreach ($this->getChildren() as $child) {
95 ++$count;
96 }
97
98 return $count;
99 }
100
101 public function __toString(): string
102 {
103 return $this->value;
104 }
105 }