1: <?php
2: 3: 4: 5: 6: 7: 8:
9: class AMysql_Iterator implements SeekableIterator
10: {
11:
12: protected $_stmt;
13: protected $_count;
14: protected $_lastFetch;
15: protected $_currentIndex = 0;
16: protected $_resultIndex = 0;
17:
18: public function __construct(AMysql_Statement $stmt)
19: {
20: $isValidSelectResult = $stmt->result instanceof Mysqli_Result || is_resource($stmt->result);
21: if (!$isValidSelectResult) {
22: throw new LogicException("Statement is not a SELECT statement. ".
23: "Unable to iterate. Query: " . $stmt->query);
24: }
25: $count = $stmt->numRows();
26: $this->_stmt = $stmt;
27: $this->_count = $count;
28: }
29:
30: public function current()
31: {
32: if ($this->_resultIndex == $this->_currentIndex + 1) {
33: return $this->_lastFetch;
34: }
35: $ret = $this->_stmt->fetch();
36: $this->_resultIndex++;
37: $this->_lastFetch = $ret;
38: return $ret;
39: }
40:
41: public function key()
42: {
43: return $this->_currentIndex;
44: }
45:
46: public function next()
47: {
48: $this->_currentIndex++;
49: }
50:
51: public function rewind()
52: {
53: if ($this->_count) {
54: $this->seek(0);
55: }
56: }
57:
58: public function valid()
59: {
60: if (0 <= $this->_currentIndex && $this->_currentIndex < $this->_count) {
61: return true;
62: }
63: return false;
64: }
65:
66: public function seek($index)
67: {
68: $isMysqli = $this->_stmt->isMysqli;
69: if (0 <= $index && $index < $this->_count) {
70: $isMysqli ? $this->_stmt->result->data_seek($index) : mysql_data_seek($this->_stmt->result, $index);
71: $this->_resultIndex = $index;
72: $this->_currentIndex = $index;
73: }
74: else {
75: throw new OutOfBoundsException("Cannot seek to position `$index`.");
76: }
77: }
78: }
79: