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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
|
<?php
/**
* Efficiently run operations on batches of results for any function
* that supports an options array.
*
* This is usually used with elgg_get_entities() and friends,
* elgg_get_annotations(), and elgg_get_metadata().
*
* If you pass a valid PHP callback, all results will be run through that
* callback. You can still foreach() through the result set after. Valid
* PHP callbacks can be a string, an array, or a closure.
* {@link http://php.net/manual/en/language.pseudo-types.php}
*
* The callback function must accept 3 arguments: an entity, the getter
* used, and the options used.
*
* Results from the callback are stored in callbackResult. If the callback
* returns only booleans, callbackResults will be the combined result of
* all calls. If no entities are processed, callbackResults will be null.
*
* If the callback returns anything else, callbackresult will be an indexed
* array of whatever the callback returns. If returning error handling
* information, you should include enough information to determine which
* result you're referring to.
*
* Don't combine returning bools and returning something else.
*
* Note that returning false will not stop the foreach.
*
* @warning If your callback or foreach loop deletes or disable entities
* you MUST call setIncrementOffset(false) or set that when instantiating.
* This forces the offset to stay what it was in the $options array.
*
* @example
* <code>
* // using foreach
* $batch = new ElggBatch('elgg_get_entities', array());
* $batch->setIncrementOffset(false);
*
* foreach ($batch as $entity) {
* $entity->disable();
* }
*
* // using both a callback
* $callback = function($result, $getter, $options) {
* var_dump("Looking at annotation id: $result->id");
* return true;
* }
*
* $batch = new ElggBatch('elgg_get_annotations', array('guid' => 2), $callback);
* </code>
*
* @package Elgg.Core
* @subpackage DataModel
* @link http://docs.elgg.org/DataModel/ElggBatch
* @since 1.8
*/
class ElggBatch
implements Iterator {
/**
* The objects to interator over.
*
* @var array
*/
private $results = array();
/**
* The function used to get results.
*
* @var mixed A string, array, or closure, or lamda function
*/
private $getter = null;
/**
* The number of results to grab at a time.
*
* @var int
*/
private $chunkSize = 25;
/**
* A callback function to pass results through.
*
* @var mixed A string, array, or closure, or lamda function
*/
private $callback = null;
/**
* Start after this many results.
*
* @var int
*/
private $offset = 0;
/**
* Stop after this many results.
*
* @var int
*/
private $limit = 0;
/**
* Number of processed results.
*
* @var int
*/
private $retrievedResults = 0;
/**
* The index of the current result within the current chunk
*
* @var int
*/
private $resultIndex = 0;
/**
* The index of the current chunk
*
* @var int
*/
private $chunkIndex = 0;
/**
* The number of results iterated through
*
* @var int
*/
private $processedResults = 0;
/**
* Is the getter a valid callback
*
* @var bool
*/
private $validGetter = null;
/**
* The result of running all entities through the callback function.
*
* @var mixed
*/
public $callbackResult = null;
/**
* If false, offset will not be incremented. This is used for callbacks/loops that delete.
*
* @var bool
*/
private $incrementOffset = true;
/**
* Entities that could not be instantiated during a fetch
*
* @var stdClass[]
*/
private $incompleteEntities = array();
/**
* Total number of incomplete entities fetched
*
* @var int
*/
private $totalIncompletes = 0;
/**
* Batches operations on any elgg_get_*() or compatible function that supports
* an options array.
*
* Instead of returning all objects in memory, it goes through $chunk_size
* objects, then requests more from the server. This avoids OOM errors.
*
* @param string $getter The function used to get objects. Usually
* an elgg_get_*() function, but can be any valid PHP callback.
* @param array $options The options array to pass to the getter function. If limit is
* not set, 10 is used as the default. In most cases that is not
* what you want.
* @param mixed $callback An optional callback function that all results will be passed
* to upon load. The callback needs to accept $result, $getter,
* $options.
* @param int $chunk_size The number of entities to pull in before requesting more.
* You have to balance this between running out of memory in PHP
* and hitting the db server too often.
* @param bool $inc_offset Increment the offset on each fetch. This must be false for
* callbacks that delete rows. You can set this after the
* object is created with {@see ElggBatch::setIncrementOffset()}.
*/
public function __construct($getter, $options, $callback = null, $chunk_size = 25,
$inc_offset = true) {
$this->getter = $getter;
$this->options = $options;
$this->callback = $callback;
$this->chunkSize = $chunk_size;
$this->setIncrementOffset($inc_offset);
if ($this->chunkSize <= 0) {
$this->chunkSize = 25;
}
// store these so we can compare later
$this->offset = elgg_extract('offset', $options, 0);
$this->limit = elgg_extract('limit', $options, 10);
// if passed a callback, create a new ElggBatch with the same options
// and pass each to the callback.
if ($callback && is_callable($callback)) {
$batch = new ElggBatch($getter, $options, null, $chunk_size, $inc_offset);
$all_results = null;
foreach ($batch as $result) {
if (is_string($callback)) {
$result = $callback($result, $getter, $options);
} else {
$result = call_user_func_array($callback, array($result, $getter, $options));
}
if (!isset($all_results)) {
if ($result === true || $result === false || $result === null) {
$all_results = $result;
} else {
$all_results = array();
}
}
if (($result === true || $result === false || $result === null) && !is_array($all_results)) {
$all_results = $result && $all_results;
} else {
$all_results[] = $result;
}
}
$this->callbackResult = $all_results;
}
}
/**
* Tell the process that an entity was incomplete during a fetch
*
* @param stdClass $row
*
* @access private
*/
public function reportIncompleteEntity(stdClass $row) {
$this->incompleteEntities[] = $row;
}
/**
* Fetches the next chunk of results
*
* @return bool
*/
private function getNextResultsChunk() {
// always reset results.
$this->results = array();
if (!isset($this->validGetter)) {
$this->validGetter = is_callable($this->getter);
}
if (!$this->validGetter) {
return false;
}
$limit = $this->chunkSize;
// if someone passed limit = 0 they want everything.
if ($this->limit != 0) {
if ($this->retrievedResults >= $this->limit) {
return false;
}
// if original limit < chunk size, set limit to original limit
// else if the number of results we'll fetch if greater than the original limit
if ($this->limit < $this->chunkSize) {
$limit = $this->limit;
} elseif ($this->retrievedResults + $this->chunkSize > $this->limit) {
// set the limit to the number of results remaining in the original limit
$limit = $this->limit - $this->retrievedResults;
}
}
if ($this->incrementOffset) {
$offset = $this->offset + $this->retrievedResults;
} else {
$offset = $this->offset + $this->totalIncompletes;
}
$current_options = array(
'limit' => $limit,
'offset' => $offset,
'__ElggBatch' => $this,
);
$options = array_merge($this->options, $current_options);
$this->incompleteEntities = array();
$this->results = call_user_func_array($this->getter, array($options));
$num_results = count($this->results);
$num_incomplete = count($this->incompleteEntities);
$this->totalIncompletes += $num_incomplete;
if ($this->incompleteEntities) {
// pad the front of the results with nulls representing the incompletes
array_splice($this->results, 0, 0, array_pad(array(), $num_incomplete, null));
// ...and skip past them
reset($this->results);
for ($i = 0; $i < $num_incomplete; $i++) {
next($this->results);
}
}
if ($this->results) {
$this->chunkIndex++;
// let the system know we've jumped past the nulls
$this->resultIndex = $num_incomplete;
$this->retrievedResults += ($num_results + $num_incomplete);
if ($num_results == 0) {
// This fetch was *all* incompletes! We need to fetch until we can either
// offer at least one row to iterate over, or give up.
return $this->getNextResultsChunk();
}
return true;
} else {
return false;
}
}
/**
* Increment the offset from the original options array? Setting to
* false is required for callbacks that delete rows.
*
* @param bool $increment Set to false when deleting data
* @return void
*/
public function setIncrementOffset($increment = true) {
$this->incrementOffset = (bool) $increment;
}
/**
* Implements Iterator
*/
/**
* PHP Iterator Interface
*
* @see Iterator::rewind()
* @return void
*/
public function rewind() {
$this->resultIndex = 0;
$this->retrievedResults = 0;
$this->processedResults = 0;
// only grab results if we haven't yet or we're crossing chunks
if ($this->chunkIndex == 0 || $this->limit > $this->chunkSize) {
$this->chunkIndex = 0;
$this->getNextResultsChunk();
}
}
/**
* PHP Iterator Interface
*
* @see Iterator::current()
* @return mixed
*/
public function current() {
return current($this->results);
}
/**
* PHP Iterator Interface
*
* @see Iterator::key()
* @return int
*/
public function key() {
return $this->processedResults;
}
/**
* PHP Iterator Interface
*
* @see Iterator::next()
* @return mixed
*/
public function next() {
// if we'll be at the end.
if (($this->processedResults + 1) >= $this->limit && $this->limit > 0) {
$this->results = array();
return false;
}
// if we'll need new results.
if (($this->resultIndex + 1) >= $this->chunkSize) {
if (!$this->getNextResultsChunk()) {
$this->results = array();
return false;
}
$result = current($this->results);
} else {
// the function above resets the indexes, so only inc if not
// getting new set
$this->resultIndex++;
$result = next($this->results);
}
$this->processedResults++;
return $result;
}
/**
* PHP Iterator Interface
*
* @see Iterator::valid()
* @return bool
*/
public function valid() {
if (!is_array($this->results)) {
return false;
}
$key = key($this->results);
return ($key !== NULL && $key !== FALSE);
}
}
|