1: <?php
2:
3: /**
4: * This file is part of the "dibi" - smart database abstraction layer.
5: *
6: * Copyright (c) 2005, 2010 David Grudl (http://davidgrudl.com)
7: *
8: * This source file is subject to the "dibi license", and/or
9: * GPL license. For more information please see http://dibiphp.com
10: * @package dibi
11: */
12:
13:
14:
15: /**
16: * External result set iterator.
17: *
18: * This can be returned by DibiResult::getIterator() method or using foreach
19: * <code>
20: * $result = dibi::query('SELECT * FROM table');
21: * foreach ($result as $row) {
22: * print_r($row);
23: * }
24: * unset($result);
25: * </code>
26: *
27: * @author David Grudl
28: */
29: class DibiResultIterator implements Iterator, Countable
30: {
31: /** @var DibiResult */
32: private $result;
33:
34: /** @var int */
35: private $row;
36:
37: /** @var int */
38: private $pointer;
39:
40:
41: /**
42: * @param DibiResult
43: */
44: public function __construct(DibiResult $result)
45: {
46: $this->result = $result;
47: }
48:
49:
50:
51: /**
52: * Rewinds the iterator to the first element.
53: * @return void
54: */
55: public function rewind()
56: {
57: $this->pointer = 0;
58: $this->result->seek(0);
59: $this->row = $this->result->fetch();
60: }
61:
62:
63:
64: /**
65: * Returns the key of the current element.
66: * @return mixed
67: */
68: public function key()
69: {
70: return $this->pointer;
71: }
72:
73:
74:
75: /**
76: * Returns the current element.
77: * @return mixed
78: */
79: public function current()
80: {
81: return $this->row;
82: }
83:
84:
85:
86: /**
87: * Moves forward to next element.
88: * @return void
89: */
90: public function next()
91: {
92: $this->row = $this->result->fetch();
93: $this->pointer++;
94: }
95:
96:
97:
98: /**
99: * Checks if there is a current element after calls to rewind() or next().
100: * @return bool
101: */
102: public function valid()
103: {
104: return !empty($this->row);
105: }
106:
107:
108:
109: /**
110: * Required by the Countable interface.
111: * @return int
112: */
113: public function count()
114: {
115: return $this->result->getRowCount();
116: }
117:
118: }
119: