@@ -32,12 +32,14 @@ class Scroll implements \Iterator
32
32
33
33
/**
34
34
* 0: scroll<br>
35
- * 1: scroll id<br>
36
- * 2: search type.
35
+ * 1: scroll id
37
36
*
38
37
* @var array
39
38
*/
40
- protected $ _options = [null , null , null ];
39
+ protected $ _options = [null , null ];
40
+
41
+ private $ totalPages = 0 ;
42
+ private $ currentPage = 0 ;
41
43
42
44
/**
43
45
* Constructor.
@@ -70,13 +72,21 @@ public function current()
70
72
*/
71
73
public function next ()
72
74
{
73
- $ this ->_saveOptions ();
75
+ if ($ this ->currentPage < $ this ->totalPages ) {
76
+ $ this ->_saveOptions ();
74
77
75
- $ this ->_search ->setOption (Search::OPTION_SCROLL , $ this ->expiryTime );
76
- $ this ->_search ->setOption (Search::OPTION_SCROLL_ID , $ this ->_nextScrollId );
77
- $ this ->_setScrollId ($ this ->_search ->search ());
78
+ $ this ->_search ->setOption (Search::OPTION_SCROLL , $ this ->expiryTime );
79
+ $ this ->_search ->setOption (Search::OPTION_SCROLL_ID , $ this ->_nextScrollId );
78
80
79
- $ this ->_revertOptions ();
81
+ $ this ->_setScrollId ($ this ->_search ->search ());
82
+
83
+ $ this ->_revertOptions ();
84
+ } else {
85
+ // If there are no pages left, we do not need to query ES.
86
+ // Reset scroll ID so valid() returns false.
87
+ $ this ->_nextScrollId = null ;
88
+ $ this ->_currentResultSet = null ;
89
+ }
80
90
}
81
91
82
92
/**
@@ -100,10 +110,7 @@ public function key()
100
110
*/
101
111
public function valid ()
102
112
{
103
- return
104
- $ this ->_nextScrollId !== null
105
- && $ this ->_currentResultSet !== null
106
- && $ this ->_currentResultSet ->count () > 0 ;
113
+ return $ this ->_nextScrollId !== null ;
107
114
}
108
115
109
116
/**
@@ -114,8 +121,8 @@ public function valid()
114
121
public function rewind ()
115
122
{
116
123
// reset state
117
- $ this ->_nextScrollId = null ;
118
- $ this ->_options = [ null , null , null ] ;
124
+ $ this ->_options = [ null , null ] ;
125
+ $ this ->currentPage = 0 ;
119
126
120
127
// initial search
121
128
$ this ->_saveOptions ();
@@ -135,11 +142,9 @@ public function rewind()
135
142
protected function _setScrollId (ResultSet $ resultSet )
136
143
{
137
144
$ this ->_currentResultSet = $ resultSet ;
138
-
139
- $ this ->_nextScrollId = null ;
140
- if ($ resultSet ->getResponse ()->isOk ()) {
141
- $ this ->_nextScrollId = $ resultSet ->getResponse ()->getScrollId ();
142
- }
145
+ $ this ->currentPage ++;
146
+ $ this ->totalPages = $ resultSet ->count () > 0 ? ceil ($ resultSet ->getTotalHits () / $ resultSet ->count ()) : 0 ;
147
+ $ this ->_nextScrollId = $ resultSet ->getResponse ()->isOk () ? $ resultSet ->getResponse ()->getScrollId () : null ;
143
148
}
144
149
145
150
/**
0 commit comments