-
Notifications
You must be signed in to change notification settings - Fork 0
/
spreader_helpers.php
67 lines (63 loc) · 1.44 KB
/
spreader_helpers.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
<?
/**
* Because Python got it right.
*/
class StopIteration extends Exception {}
/**
* Converts a PHP-style iterable into a Python-style iterable.
* ->next() returns values until the iterable is empty, then starts raising StopIteration.
*/
class PHP2PyIterator {
function __construct($iterator) {
$this->iterator = $iterator;
}
function next() {
list($key, $value) = each($this->iterator);
if ($key === NULL) {
throw new StopIteration();
}
return $value;
}
}
/**
* Converts a Python-style iterable into a PHP-style iterable.
* Returns a constant key() and doesn't implement rewind();
* foreach() doesn't need them, and neither do you.
* If you're using each() just make sure you check
* key === NULL, because (0 == NULL) == TRUE.
* Yes that's intentional, it's to make sure you do it right.
*/
class Py2PHPIterator implements Iterator {
function __construct($py_iterator) {
$this->py_iterator = $py_iterator;
$this->next();
}
function current() {
return $this->current_value;
}
function key() {
return 0;
}
function next() {
try {
$this->current_value = $this->py_iterator->next();
$this->valid = TRUE;
} catch (StopIteration $e) {
$this->current_value = FALSE;
$this->valid = FALSE;
}
}
function rewind() {
/* Do nothing */
}
function valid() {
return $this->valid;
}
}
function iterator2array($iterator) {
$array = array();
foreach ($iterator as $value) {
$array[] = $value;
}
return $array;
}