summaryrefslogtreecommitdiff
path: root/ext/spl/examples/cachingiterator.inc
blob: ac2476f1f823ac4e99f82ed1cafdfb1fda9305d9 (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
<?php

define('CIT_CALL_TOSTRING', 1);
define('CIT_CATCH_GET_CHILD', 2);

class CachingIterator
{
	protected $it;
	protected $current;
	protected $key;
	protected $valid;
	protected $strValue;

	function __construct(Iterator $it, $flags = CIT_CALL_TOSTRING)
	{
		$this->it = $it;
		$this->flags = $flags & (CIT_CALL_TOSTRING|CIT_CATCH_GET_CHILD);
		$this->next();
	}

	function rewind()
	{
		$this->it->rewind();
		$this->next();
	}
	
	function next()
	{
		if ($this->valid = $this->it->valid()) {
			$this->current = $this->it->current();
			$this->key = $this->it->key();
			if ($this->flags & CIT_CALL_TOSTRING) {
				if (is_object($this->current)) {
					$this->strValue = $this->current->__toString();
				} else {
					$this->strValue = (string)$this->current;
				}
			}
		} else {
			$this->current = NULL;
			$this->key = NULL;
			$this->strValue = NULL;
		}
		$this->it->next();
	}
	
	function valid()
	{
		return $this->valid;
	}

	function hasNext()
	{
		return $this->it->valid();
	}
	
	function current()
	{
		return $this->current;
	}

	function key()
	{
		return $this->key;
	}

	function __call($func, $params)
	{
		return call_user_func_array(array($this->it, $func), $params);
	}
	
	function __toString()
	{
		if (!$this->flags & CIT_CALL_TOSTRING) {
			throw new exception('CachingIterator does not fetch string value (see CachingIterator::__construct)');
		}
		return $this->strValue;
	}
}

?>