1+ <?php
2+
3+
4+ namespace Dababo \LazyChunk ;
5+
6+
7+ use Illuminate \Support \LazyCollection ;
8+
9+ class LazyChunkMixin
10+ {
11+ public function lazyChunk ()
12+ {
13+ return function ($ count , callable $ callback = null ) {
14+ return new LazyCollection (function () use ($ count , $ callback ) {
15+
16+ $ this ->enforceOrderBy ();
17+
18+ $ page = 1 ;
19+
20+ do {
21+ // We'll execute the query for the given page and get the results. If there are
22+ // no results we can just break and return from here. When there are results
23+ // we will call the callback with the current chunk of these results here.
24+ $ results = $ this ->forPage ($ page , $ count )->get ();
25+
26+ $ countResults = $ results ->count ();
27+
28+ if ($ countResults == 0 ) {
29+ break ;
30+ }
31+
32+ yield $ page => $ results ;
33+
34+ if ($ callback !== null && $ callback ($ results , $ page ) === false ) {
35+ break ;
36+ }
37+
38+ unset($ results );
39+
40+ $ page ++;
41+ } while ($ countResults == $ count );
42+ });
43+ };
44+ }
45+
46+ public function flatLazyChunk ()
47+ {
48+ return function ($ count , callable $ callback = null ) {
49+ return $ this ->lazyChunk ($ count , $ callback )->flatten (1 );
50+ };
51+ }
52+
53+ public function lazyChunkById ()
54+ {
55+ return function ($ count , callable $ callback = null , $ column = null , $ alias = null ) {
56+ return new LazyCollection (function () use ($ count , $ callback , $ column , $ alias ) {
57+ $ column = $ column ?? $ this ->defaultKeyName ();
58+
59+ $ alias = $ alias ?? $ column ;
60+
61+ $ lastId = null ;
62+
63+ do {
64+ $ clone = clone $ this ;
65+
66+ // We'll execute the query for the given page and get the results. If there are
67+ // no results we can just break and return from here. When there are results
68+ // we will call the callback with the current chunk of these results here.
69+ $ results = $ clone ->forPageAfterId ($ count , $ lastId , $ column )->get ();
70+
71+ $ countResults = $ results ->count ();
72+
73+ if ($ countResults == 0 ) {
74+ break ;
75+ }
76+
77+ yield $ results ;
78+
79+ // On each chunk result set, we will pass them to the callback and then let the
80+ // developer take care of everything within the callback, which allows us to
81+ // keep the memory low for spinning through large result sets for working.
82+ if ($ callback !== null && $ callback ($ results ) === false ) {
83+ return false ;
84+ }
85+
86+ $ lastId = $ results ->last ()->{$ alias };
87+
88+ unset($ results );
89+ } while ($ countResults == $ count );
90+ });
91+ };
92+ }
93+
94+ public function flatLazyChunkById ()
95+ {
96+ return function ($ count , callable $ callable = null , $ column = null , $ alias = null ) {
97+ return $ this ->lazyChunkById ($ count , $ callable , $ column , $ alias )->flatten (1 );
98+ };
99+ }
100+ }
0 commit comments