xref: /PHP-5.6/ext/spl/internal/filteriterator.inc (revision 1b9e0de2)
1<?php
2
3/** @file filteriterator.inc
4 * @ingroup SPL
5 * @brief class FilterIterator
6 * @author  Marcus Boerger
7 * @date    2003 - 2009
8 *
9 * SPL - Standard PHP Library
10 */
11
12/**
13 * @brief   Abstract filter for iterators
14 * @author  Marcus Boerger
15 * @version 1.1
16 * @since PHP 5.0
17 *
18 * Instances of this class act as a filter around iterators. In other words
19 * you can put an iterator into the constructor and the instance will only
20 * return selected (accepted) elements.
21 *
22 * The only thing that needs to be done to make this work is implementing
23 * method accept(). Typically this invloves reading the current element or
24 * key of the inner Iterator and checking whether it is acceptable.
25 */
26abstract class FilterIterator implements OuterIterator
27{
28	private $it;
29
30	/**
31	 * Constructs a filter around another iterator.
32	 *
33	 * @param it     Iterator to filter
34	 */
35	function __construct(Iterator $it) {
36		$this->it = $it;
37	}
38
39	/**
40	 * Rewind the inner iterator.
41	 */
42	function rewind() {
43		$this->it->rewind();
44		$this->fetch();
45	}
46
47	/**
48	 * Accept function to decide whether an element of the inner iterator
49	 * should be accessible through the Filteriterator.
50	 *
51	 * @return whether or not to expose the current element of the inner
52	 *         iterator.
53	 */
54	abstract function accept();
55
56	/**
57	 * Fetch next element and store it.
58	 *
59	 * @return void
60	 */
61	protected function fetch() {
62		while ($this->it->valid()) {
63			if ($this->accept()) {
64				return;
65			}
66			$this->it->next();
67		};
68	}
69
70	/**
71	 * Move to next element
72	 *
73	 * @return void
74	 */
75	function next() {
76		$this->it->next();
77		$this->fetch();
78	}
79
80	/**
81	 * @return Whether more elements are available
82	 */
83	function valid() {
84		return $this->it->valid();
85	}
86
87	/**
88	 * @return The current key
89	 */
90	function key() {
91		return $this->it->key();
92	}
93
94	/**
95	 * @return The current value
96	 */
97	function current() {
98		return $this->it->current();
99	}
100
101	/**
102	 * hidden __clone
103	 */
104	protected function __clone() {
105		// disallow clone
106	}
107
108	/**
109	 * @return The inner iterator
110	 */
111	function getInnerIterator()
112	{
113		return $this->it;
114	}
115
116	/** Aggregate the inner iterator
117	 *
118	 * @param func    Name of method to invoke
119	 * @param params  Array of parameters to pass to method
120	 */
121	function __call($func, $params)
122	{
123		return call_user_func_array(array($this->it, $func), $params);
124	}
125}
126
127?>