@@ -27,48 +27,44 @@ public function __construct( BatchFactory $factory )
27
27
$ this ->factory = $ factory ;
28
28
}
29
29
30
- public function get ( $ limit = 50 , $ before = null ): array
30
+ public function get ($ limit = 50 , $ before = null ): array
31
31
{
32
- if ( !Redis::exists ( 'batches_list ' ) ) {
32
+ if (!Redis::exists ('batches_list ' ) ) {
33
33
return [];
34
34
}
35
35
36
- $ totalBatches = Redis::llen ( 'batches_list ' );
36
+ $ totalBatches = Redis::llen ('batches_list ' );
37
37
38
- // Determine the starting index
39
- $ startIndex = 0 ;
40
- if ( $ before !== null ) {
41
- $ rangeSize = 100 ;
42
- $ allBatchIds = Redis::lrange ( 'batches_list ' , 0 , $ rangeSize - 1 );
43
- $ beforeIndex = array_search ( $ before , $ allBatchIds );
38
+ // If $before is specified, find its index
39
+ $ beforeIndex = $ before ? array_search ($ before , Redis::lrange ('batches_list ' , 0 , -1 )) : null ;
44
40
45
- if ( $ beforeIndex !== false ) {
46
- $ startIndex = $ beforeIndex + 1 ;
47
- }
48
- // Handle cases where 'before' is not found or other scenarios
41
+ // Determine the range to fetch
42
+ if ($ beforeIndex !== false && $ beforeIndex !== null ) {
43
+ $ rangeEnd = $ beforeIndex - 1 ;
44
+ $ startIndex = max ($ rangeEnd - $ limit + 1 , 0 );
45
+ } else {
46
+ $ startIndex = max ($ totalBatches - $ limit , 0 );
47
+ $ rangeEnd = $ totalBatches - 1 ;
49
48
}
50
49
51
- // Calculate the range to fetch
52
- $ rangeEnd = min ( $ startIndex + $ limit - 1 , $ totalBatches - 1 );
53
-
54
50
// Fetch only the required batch IDs
55
- $ batchIds = Redis::lrange ( 'batches_list ' , $ startIndex , $ rangeEnd );
51
+ $ batchIds = Redis::lrange ('batches_list ' , $ startIndex , $ rangeEnd );
56
52
57
53
// Use Redis pipeline to bulk fetch batch data
58
- $ responses = Redis::pipeline ( function ( $ pipe ) use ( $ batchIds ) {
59
- foreach ( $ batchIds as $ batchId ) {
60
- $ pipe ->get ( "batch: $ batchId " );
54
+ $ responses = Redis::pipeline (function ($ pipe ) use ($ batchIds ) {
55
+ foreach ($ batchIds as $ batchId ) {
56
+ $ pipe ->get ("batch: $ batchId " );
61
57
}
62
- } );
58
+ });
63
59
64
60
// Filter, decode, and sort raw batch data
65
- $ batchesRaw = array_map ( fn ( $ response ) => json_decode ( $ response , true ), array_filter ( $ responses ) );
66
- uasort ( $ batchesRaw , function ( $ a , $ b ) {
61
+ $ batchesRaw = array_map (fn ($ response ) => json_decode ($ response , true ), array_filter ($ responses) );
62
+ uasort ($ batchesRaw , function ($ a , $ b ) {
67
63
return $ b ['created_at ' ] <=> $ a ['created_at ' ];
68
- } );
64
+ });
69
65
70
66
// Map sorted data to Batch objects and convert to a sequential array
71
- $ batches = array_values ( array_map ( fn ( $ data ) => $ this ->toBatch ( $ data ), $ batchesRaw ) );
67
+ $ batches = array_values (array_map (fn ($ data ) => $ this ->toBatch ($ data ), $ batchesRaw) );
72
68
73
69
return $ batches ;
74
70
}
0 commit comments