summaryrefslogtreecommitdiff
path: root/ext/spl/internal/filteriterator.inc
blob: 3330cc9e47ec7184ff4aa05dbc34364438505843 (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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php

/** @file filteriterator.inc
 * @ingroup SPL
 * @brief class FilterIterator
 * @author  Marcus Boerger
 * @date    2003 - 2009
 *
 * SPL - Standard PHP Library
 */

/**
 * @brief   Abstract filter for iterators
 * @author  Marcus Boerger
 * @version 1.1
 * @since PHP 5.0
 *
 * Instances of this class act as a filter around iterators. In other words 
 * you can put an iterator into the constructor and the instance will only 
 * return selected (accepted) elements.
 *
 * The only thing that needs to be done to make this work is implementing 
 * method accept(). Typically this invloves reading the current element or 
 * key of the inner Iterator and checking whether it is acceptable.
 */
abstract class FilterIterator implements OuterIterator
{
	private $it;

	/**
	 * Constructs a filter around another iterator.
	 *
	 * @param it     Iterator to filter
	 */
	function __construct(Iterator $it) {
		$this->it = $it;
	}

	/**
	 * Rewind the inner iterator.
	 */
	function rewind() {	
		$this->it->rewind();
		$this->fetch();
	}

	/**
	 * Accept function to decide whether an element of the inner iterator
	 * should be accessible through the Filteriterator.
	 *
	 * @return whether or not to expose the current element of the inner
	 *         iterator.
	 */
	abstract function accept();

	/**
	 * Fetch next element and store it.
	 *
	 * @return void
	 */
	protected function fetch() {
		while ($this->it->valid()) {
			if ($this->accept()) {
				return;
			}
			$this->it->next();
		};
	}

	/**
	 * Move to next element
	 *
	 * @return void
	 */
	function next() {
		$this->it->next();
		$this->fetch();
	}
	
	/**
	 * @return Whether more elements are available
	 */
	function valid() {
		return $this->it->valid();
	}
	
	/**
	 * @return The current key
	 */
	function key() {
		return $this->it->key();
	}
	
	/**
	 * @return The current value
	 */
	function current() {
		return $this->it->current();
	}
	
	/**
	 * hidden __clone
	 */
	protected function __clone() {
		// disallow clone 
	}

	/**
	 * @return The inner iterator
	 */	
	function getInnerIterator()
	{
		return $this->it;
	}

	/** Aggregate the inner iterator
	 *
	 * @param func    Name of method to invoke
	 * @param params  Array of parameters to pass to method
	 */
	function __call($func, $params)
	{
		return call_user_func_array(array($this->it, $func), $params);
	}
}

?>