88use Illuminate \Support \Facades \Bus ;
99use Illuminate \Support \Facades \DB ;
1010use Illuminate \Support \Facades \Queue ;
11+ use Lomkit \Rest \Contracts \BatchableAction ;
1112use Lomkit \Rest \Contracts \QueryBuilder ;
1213use Lomkit \Rest \Http \Requests \OperateRequest ;
1314use Lomkit \Rest \Http \Requests \RestRequest ;
@@ -35,6 +36,12 @@ class DispatchAction
3536 */
3637 protected $ fields ;
3738
39+ /**
40+ * The pending batch instance.
41+ *
42+ * @var \Illuminate\Bus\PendingBatch|null
43+ */
44+ protected $ batchJob ;
3845
3946 /**
4047 * Create a new action dispatcher instance.
@@ -44,11 +51,38 @@ class DispatchAction
4451 * @param array $fields
4552 * @return void
4653 */
47- public function __construct (OperateRequest $ request , Action $ action , array $ fields )
54+ public function __construct (OperateRequest $ request , \ Lomkit \ Rest \ Actions \ Action $ action , array $ fields )
4855 {
4956 $ this ->request = $ request ;
5057 $ this ->action = $ action ;
5158 $ this ->fields = $ fields ;
59+
60+ if ($ action instanceof BatchableAction) {
61+ $ this ->configureBatchJob ($ action , $ fields );
62+ }
63+ }
64+
65+ /**
66+ * Configure the batch job for the action.
67+ *
68+ * @param \Lomkit\Rest\Actions\Action $action
69+ * @param array $fields
70+ * @return void
71+ */
72+ protected function configureBatchJob (\Lomkit \Rest \Actions \Action $ action , array $ fields )
73+ {
74+ $ batch = Bus::batch ([]);
75+ $ batch ->name ($ action ->uriKey ());
76+
77+ if (! is_null ($ connection = $ this ->connection ())) {
78+ $ batch ->onConnection ($ connection );
79+ }
80+ if (! is_null ($ queue = $ this ->queue ())) {
81+ $ batch ->onQueue ($ queue );
82+ }
83+
84+ $ action ->withBatch ($ fields , $ batch );
85+ $ this ->batchJob = $ batch ;
5286 }
5387
5488 /**
@@ -77,6 +111,10 @@ function ($chunk) {
77111 }
78112 );
79113
114+ if (! is_null ($ this ->batchJob )) {
115+ $ this ->batchJob ->dispatch ();
116+ }
117+
80118 return $ searchQuery ->count ();
81119 }
82120
@@ -129,13 +167,15 @@ protected function dispatchSynchronouslyForCollection(Collection $models)
129167 */
130168 protected function addQueuedActionJob ( Collection $ models )
131169 {
132- $ job = new CallRestApiAction (
133- $ this ->action , $ this ->fields , $ models
134- );
170+ $ job = new CallRestApiAction ($ this ->action , $ this ->fields , $ models );
135171
136- Queue::connection ($ this ->connection ())->pushOn (
137- $ this ->queue (), $ job
138- );
172+ if ($ this ->action instanceof BatchableAction) {
173+ $ this ->batchJob ->add ([$ job ]);
174+ } else {
175+ Queue::connection ($ this ->connection ())->pushOn (
176+ $ this ->queue (), $ job
177+ );
178+ }
139179
140180 return $ this ;
141181 }
0 commit comments