TreeNode.php 2.3 KB

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