summaryrefslogtreecommitdiff
path: root/ext/spl/examples/recursiveiteratoriterator.inc
blob: 05e31df464c0e02fb79c94f81eea58390ed1038a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php

/**
 * @brief   Iterates through recursive iterators
 * @author  Marcus Boerger
 * @version 1.0
 *
 */
class RecursiveIteratorIterator implements Iterator
{
	protected $ait = array();
	protected $count = 0;

	function __construct(RecursiveIterator $it)
	{
		$this->ait[0] = $it;
	}


	function rewind()
	{
		while ($this->count) {
			unset($this->ait[$this->count--]);
		}
		$this->ait[0]->rewind();
		$this->ait[0]->recursed = false;
	}
	
	function valid()
	{
		$count = $this->count;
		while ($count) {
			$it = $this->ait[$count];
			if ($it->valid()) {
				return true;
			}
			$count--;
		}
		return false;
	}
	
	function key()
	{
		$it = $this->ait[$this->count];
		return $it->key();
	}
	
	function current()
	{
		$it = $this->ait[$this->count];
		return $it->current();
	}
	
	function next()
	{
		while ($this->count) {
			$it = $this->ait[$this->count];
			if ($it->valid()) {
				if (!$it->recursed && $it->hasChildren()) {
					$it->recursed = true;
					$sub = $it->getChildren();
					$sub->recursed = false;
					$sub->rewind();
					if ($sub->valid()) {
						$this->ait[++$this->count] = $sub;
						if (!$sub instanceof RecursiveIterator) {
							throw new Exception(get_class($sub).'::getChildren() must return an object that implements RecursiveIterator');
						} 
						return;
					}
					unset($sub);
				}
				$it->next();
				$it->recursed = false;
				if ($it->valid()) {
					return;
				}
				$it->recursed = false;
			}
			if ($this->count) {
				unset($this->ait[$this->count--]);
				$it = $this->ait[$this->count];
			}
		}
	}
	
	function getSubIterator($level = NULL)
	{
		if (is_null($level)) {
			$level = $this->count;
		}
		return @$this->ait[$level];
	}

	function getDepth()
	{
		return $this->level;
	}
}

?>