Iterator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of phpunit/php-code-coverage.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  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 SebastianBergmann\CodeCoverage\Node;
  11. use function count;
  12. use RecursiveIterator;
  13. /**
  14. * @internal This class is not covered by the backward compatibility promise for phpunit/php-code-coverage
  15. */
  16. final class Iterator implements RecursiveIterator
  17. {
  18. private int $position;
  19. /**
  20. * @var list<AbstractNode>
  21. */
  22. private readonly array $nodes;
  23. public function __construct(Directory $node)
  24. {
  25. $this->nodes = $node->children();
  26. }
  27. /**
  28. * Rewinds the Iterator to the first element.
  29. */
  30. public function rewind(): void
  31. {
  32. $this->position = 0;
  33. }
  34. /**
  35. * Checks if there is a current element after calls to rewind() or next().
  36. */
  37. public function valid(): bool
  38. {
  39. return $this->position < count($this->nodes);
  40. }
  41. /**
  42. * Returns the key of the current element.
  43. */
  44. public function key(): int
  45. {
  46. return $this->position;
  47. }
  48. /**
  49. * Returns the current element.
  50. */
  51. public function current(): ?AbstractNode
  52. {
  53. return $this->valid() ? $this->nodes[$this->position] : null;
  54. }
  55. /**
  56. * Moves forward to next element.
  57. */
  58. public function next(): void
  59. {
  60. $this->position++;
  61. }
  62. /**
  63. * Returns the sub iterator for the current element.
  64. */
  65. public function getChildren(): self
  66. {
  67. return new self($this->nodes[$this->position]);
  68. }
  69. /**
  70. * Checks whether the current element has children.
  71. */
  72. public function hasChildren(): bool
  73. {
  74. return $this->nodes[$this->position] instanceof Directory;
  75. }
  76. }