/
Iterator.php
83 lines (69 loc) · 1.78 KB
/
Iterator.php
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
<?php
namespace SparkLib;
use InvalidArgumentException;
abstract class Iterator implements \Iterator {
protected $_useCache = false;
/**
* Require that children of this class implement a getNext()
*/
abstract public function getNext ();
/**
* Should child classes attempt to use cached return values?
*
* It's up to a child to decide what, if anything, this means.
*/
public function useCache ($value = true)
{
$this->_useCache = $value;
return $this;
}
/**
* Calls $function() on each remaining element in the iterator.
*
* @param callback $function
* @return SparkFriendFinder the finder
*/
public function each ($function)
{
if (! \is_callable($function) )
throw new InvalidArgumentException('each(): parameter is not a callback');
// handle first/current result
$rec = $this->getNext();
if (! $rec)
return $this;
call_user_func($function, $rec);
// handle the rest, if any
while ($this->valid()) {
$rec = $this->getNext();
if ($rec) {
call_user_func($function, $rec);
}
}
return $this;
}
/**
* Map iterator results to an array, using a callback function.
*
* @param callback $function
* @return array $results
*/
public function map ($function)
{
if (! \is_callable($function))
throw new InvalidArgumentException('map(): parameter is not a callback.');
$results = array();
// handle first/current result
$rec = $this->getNext();
if (! $rec)
return $results;
$results[] = call_user_func($function, $rec);
// handle the rest, if any
while ($this->valid()) {
$rec = $this->getNext();
if ($rec) {
$results[] = call_user_func($function, $rec);
}
}
return $results;
}
}