1 <?php
2 /**
3 * Neevo - Tiny database layer for PHP. (http://neevo.smasty.net)
4 *
5 * This source file is subject to the MIT license that is bundled
6 * with this package in the file license.txt.
7 *
8 * Copyright (c) 2012 Smasty (http://smasty.net)
9 *
10 */
11
12 namespace Neevo;
13
14 use Countable;
15 use Exception;
16 use Iterator;
17 use OutOfRangeException;
18 use SeekableIterator;
19
20
21 /**
22 * Result set iterator.
23 * @author Smasty
24 */
25 class ResultIterator implements Iterator, Countable, SeekableIterator {
26
27
28 /** @var int */
29 private $pointer;
30
31 /** @var Result */
32 private $result;
33
34 /** @var Row */
35 private $row;
36
37
38 public function __construct(Result $result){
39 $this->result = $result;
40 }
41
42
43 /**
44 * Rewinds the iterator.
45 * For future iterations seeks if possible, clones otherwise.
46 */
47 public function rewind(){
48 try{
49 $count = count($this);
50 } catch(DriverException $e){
51 $count = -1;
52 }
53 if($this->row !== null && $count > 0){
54 try{
55 $this->seek(0);
56 } catch(DriverException $e){
57 $clone = clone $this->result;
58 $this->result->__destruct();
59 $this->result = $clone;
60 $this->pointer = 0;
61 $this->row = $this->result->fetch();
62 }
63 } else{
64 $this->pointer = 0;
65 $this->row = $this->result->fetch();
66 }
67 }
68
69
70 /**
71 * Moves to next row.
72 */
73 public function next(){
74 $this->row = $this->result->fetch();
75 $this->pointer++;
76 }
77
78
79 /**
80 * Checks for valid current row.
81 * @return bool
82 */
83 public function valid(){
84 return $this->row !== false;
85 }
86
87
88 /**
89 * Returns the current row.
90 * @return Row
91 */
92 public function current(){
93 return $this->row;
94 }
95
96
97 /**
98 * Returns the key of current row.
99 * @return int
100 */
101 public function key(){
102 return $this->pointer;
103 }
104
105
106 /**
107 * Implementation of Countable.
108 * @return int
109 * @throws DriverException on unbuffered result.
110 */
111 public function count(){
112 return $this->result->count();
113 }
114
115
116 /**
117 * Implementation of SeekableIterator.
118 * @param int $offset
119 * @throws OutOfRangeException|DriverException
120 */
121 public function seek($offset){
122 try{
123 $this->result->seek($offset);
124 } catch(DriverException $e){
125 throw $e;
126 } catch(NeevoException $e){
127 throw new OutOfRangeException("Cannot seek to offset $offset.", null, $e);
128 }
129 $this->row = $this->result->fetch();
130 $this->pointer = $offset;
131 }
132
133
134 }
135