@@ -8,11 +8,50 @@ class UnionBuilder implements Builder
8
8
{
9
9
private array $ queryCalls = [];
10
10
private array $ outerQueryCalls = [];
11
+ private ?int $ limit = null ;
12
+ private int $ offset = 0 ;
11
13
12
14
public function __construct (protected array $ queries )
13
15
{
14
16
}
15
17
18
+ public function skip (int $ value ): static
19
+ {
20
+ return $ this ->offset ($ value );
21
+ }
22
+
23
+ public function offset (int $ value ): static
24
+ {
25
+ $ this ->offset = max (0 , $ value );
26
+
27
+ return $ this ;
28
+ }
29
+
30
+ public function take (?int $ value ): static
31
+ {
32
+ return $ this ->limit ($ value );
33
+ }
34
+
35
+ public function limit (?int $ value ): static
36
+ {
37
+ if ($ value >= 0 ) {
38
+ $ this ->limit = $ value ;
39
+ }
40
+
41
+ return $ this ;
42
+ }
43
+
44
+ public function orderBy ($ column , $ direction = 'asc ' ): static
45
+ {
46
+ $ this ->queryCalls [] = fn ($ query ) => $ query
47
+ ->addSelect ($ column )
48
+ ->orderBy ($ column , $ direction );
49
+
50
+ $ this ->outerQueryCalls [] = fn ($ query ) => $ query ->orderBy ($ column , $ direction );
51
+
52
+ return $ this ;
53
+ }
54
+
16
55
public function count ($ columns = '* ' ): int
17
56
{
18
57
return $ this ->buildQuery ()->count ($ columns );
@@ -31,6 +70,10 @@ protected function buildQuery()
31
70
foreach ($ this ->queryCalls as $ call ) {
32
71
$ call ($ query );
33
72
}
73
+
74
+ if ($ this ->limit ) {
75
+ $ query ->take ($ this ->offset + $ this ->limit );
76
+ }
34
77
}
35
78
36
79
$ outerQuery = array_shift ($ queries );
@@ -43,20 +86,16 @@ protected function buildQuery()
43
86
$ call ($ outerQuery );
44
87
}
45
88
89
+ if ($ this ->limit ) {
90
+ $ outerQuery ->skip ($ this ->offset )->take ($ this ->limit );
91
+ }
92
+
46
93
return $ outerQuery ;
47
94
}
48
95
49
96
public function __call ($ method , $ parameters )
50
97
{
51
- $ call = $ this ->queryCalls [] = fn ($ query ) => $ query ->$ method (...$ parameters );
52
-
53
- if ($ method === 'orderBy ' ) {
54
- $ this ->queryCalls [] = fn ($ query ) => $ query ->addSelect ($ parameters [0 ]);
55
- }
56
-
57
- if (in_array ($ method , ['take ' , 'limit ' , 'skip ' , 'offset ' , 'orderBy ' ])) {
58
- $ this ->outerQueryCalls [] = $ call ;
59
- }
98
+ $ this ->queryCalls [] = fn ($ query ) => $ query ->$ method (...$ parameters );
60
99
61
100
return $ this ;
62
101
}
0 commit comments