Iterator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /**
  19. * @var int
  20. */
  21. private $position;
  22. /**
  23. * @var AbstractNode[]
  24. */
  25. private $nodes;
  26. public function __construct(Directory $node)
  27. {
  28. $this->nodes = $node->children();
  29. }
  30. /**
  31. * Rewinds the Iterator to the first element.
  32. */
  33. public function rewind(): void
  34. {
  35. $this->position = 0;
  36. }
  37. /**
  38. * Checks if there is a current element after calls to rewind() or next().
  39. */
  40. public function valid(): bool
  41. {
  42. return $this->position < count($this->nodes);
  43. }
  44. /**
  45. * Returns the key of the current element.
  46. */
  47. public function key(): int
  48. {
  49. return $this->position;
  50. }
  51. /**
  52. * Returns the current element.
  53. */
  54. public function current(): ?AbstractNode
  55. {
  56. return $this->valid() ? $this->nodes[$this->position] : null;
  57. }
  58. /**
  59. * Moves forward to next element.
  60. */
  61. public function next(): void
  62. {
  63. $this->position++;
  64. }
  65. /**
  66. * Returns the sub iterator for the current element.
  67. */
  68. public function getChildren(): self
  69. {
  70. return new self($this->nodes[$this->position]);
  71. }
  72. /**
  73. * Checks whether the current element has children.
  74. */
  75. public function hasChildren(): bool
  76. {
  77. return $this->nodes[$this->position] instanceof Directory;
  78. }
  79. }