@@ -30,6 +30,11 @@ class Paginator
3030 */
3131 private $ promise ;
3232
33+ /**
34+ * @var int
35+ */
36+ private $ totalCount ;
37+
3338 /**
3439 * @param callable $fetcher
3540 * @param bool $promise
@@ -49,7 +54,7 @@ public function __construct(callable $fetcher, $promise = self::MODE_REGULAR)
4954 */
5055 public function backward ($ args , $ total , array $ callableArgs = [])
5156 {
52- $ total = is_callable ( $ total ) ? call_user_func_array ($ total , $ callableArgs ) : $ total ;
57+ $ total = $ this -> computeTotalCount ($ total , $ callableArgs );
5358
5459 $ args = $ this ->protectArgs ($ args );
5560 $ limit = $ args ['last ' ];
@@ -107,10 +112,20 @@ public function auto($args, $total, $callableArgs = [])
107112 $ args = $ this ->protectArgs ($ args );
108113
109114 if ($ args ['last ' ]) {
110- return $ this ->backward ($ args , $ total , $ callableArgs );
115+ $ connection = $ this ->backward ($ args , $ total , $ callableArgs );
111116 } else {
112- return $ this ->forward ($ args );
117+ $ connection = $ this ->forward ($ args );
113118 }
119+
120+ if ($ this ->promise ) {
121+ $ connection ->then (function (Connection $ connection ) use ($ total , $ callableArgs ) {
122+ $ connection ->totalCount = $ this ->computeTotalCount ($ total , $ callableArgs );
123+ });
124+ } else {
125+ $ connection ->totalCount = $ this ->computeTotalCount ($ total , $ callableArgs );
126+ }
127+
128+ return $ connection ;
114129 }
115130
116131 /**
@@ -137,4 +152,21 @@ private function protectArgs($args)
137152 {
138153 return $ args instanceof Argument ? $ args : new Argument ($ args );
139154 }
155+
156+ /**
157+ * @param int $total
158+ * @param array $callableArgs
159+ *
160+ * @return int|mixed
161+ */
162+ private function computeTotalCount ($ total , array $ callableArgs = [])
163+ {
164+ if ($ this ->totalCount !== null ) {
165+ return $ this ->totalCount ;
166+ }
167+
168+ $ this ->totalCount = is_callable ($ total ) ? call_user_func_array ($ total , $ callableArgs ) : $ total ;
169+
170+ return $ this ->totalCount ;
171+ }
140172}
0 commit comments