-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathChunkIterator.php
64 lines (54 loc) · 1.68 KB
/
ChunkIterator.php
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
<?php
namespace Coderflex\LaravelCsv\Utilities;
use Iterator;
/**
* ChunkIterator is simple class, using built-in Iterator php class.
* The use cases of this generator class is to avoid memory limit, that
* requires a considerable amount of processing time to generate.
* Instead of excuting directly in-memory, we yeild the results as
* many times as we need.
*
* @see https://www.php.net/manual/en/language.generators.overview.php
* @see https://www.php.net/manual/en/language.generators.syntax.php#control-structures.yield
* @see https://www.php.net/manual/en/language.oop5.iterations.php
*/
class ChunkIterator
{
/**
* @var Iterator
*/
protected Iterator $iterator;
/**
* @var int
*/
protected int $chunkSize;
public function __construct(Iterator $iterator, int $chunkSize)
{
$this->iterator = $iterator;
$this->chunkSize = $chunkSize;
}
/**
* Chunk the given data
*/
public function get()
{
$chunk = [];
for ($i = 0; $this->iterator->valid(); $i++) {
// store the current record into the $chunk array
$chunk[] = $this->iterator->current();
// move on to the next record
$this->iterator->next();
// if the number of element on the $chunk variable
// met the chunk size, we yield the result and start
// over, to the next elements
if (count($chunk) == $this->chunkSize) {
yield $chunk;
$chunk = [];
}
}
// if the chunk size is positive, we yield the results
if (count($chunk) > 0) {
yield $chunk;
}
}
}