1<?php
2/*
3 * This file is part of the php-code-coverage package.
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
11namespace SebastianBergmann\CodeCoverage\Node;
12
13/**
14 * Recursive iterator for node object graphs.
15 */
16class Iterator implements \RecursiveIterator
17{
18    /**
19     * @var int
20     */
21    private $position;
22
23    /**
24     * @var AbstractNode[]
25     */
26    private $nodes;
27
28    /**
29     * @param Directory $node
30     */
31    public function __construct(Directory $node)
32    {
33        $this->nodes = $node->getChildNodes();
34    }
35
36    /**
37     * Rewinds the Iterator to the first element.
38     */
39    public function rewind()
40    {
41        $this->position = 0;
42    }
43
44    /**
45     * Checks if there is a current element after calls to rewind() or next().
46     *
47     * @return bool
48     */
49    public function valid()
50    {
51        return $this->position < count($this->nodes);
52    }
53
54    /**
55     * Returns the key of the current element.
56     *
57     * @return int
58     */
59    public function key()
60    {
61        return $this->position;
62    }
63
64    /**
65     * Returns the current element.
66     *
67     * @return \PHPUnit_Framework_Test
68     */
69    public function current()
70    {
71        return $this->valid() ? $this->nodes[$this->position] : null;
72    }
73
74    /**
75     * Moves forward to next element.
76     */
77    public function next()
78    {
79        $this->position++;
80    }
81
82    /**
83     * Returns the sub iterator for the current element.
84     *
85     * @return Iterator
86     */
87    public function getChildren()
88    {
89        return new self(
90            $this->nodes[$this->position]
91        );
92    }
93
94    /**
95     * Checks whether the current element has children.
96     *
97     * @return bool
98     */
99    public function hasChildren()
100    {
101        return $this->nodes[$this->position] instanceof Directory;
102    }
103}
104