44
55use App \Models \File ;
66use App \Services \Pdf \PdfService ;
7+ use Illuminate \Bus \Batch ;
78use Illuminate \Contracts \Queue \ShouldQueue ;
89use Illuminate \Foundation \Queue \Queueable ;
910use Illuminate \Support \Facades \Bus ;
1011use Illuminate \Support \Facades \Log ;
12+ use Throwable ;
1113
1214class ProcessDocumentJob implements ShouldQueue
1315{
@@ -17,15 +19,19 @@ class ProcessDocumentJob implements ShouldQueue
1719 * Create a new job instance.
1820 */
1921 public function __construct (
20- protected File $ file ,
22+ protected int $ fileId ,
2123 ) {}
2224
2325 /**
2426 * Execute the job.
2527 */
2628 public function handle (): void
2729 {
28- $ pdfText = app (PdfService::class)->getPdfText ($ this ->file ->path );
30+ $ file = File::findOrFail ($ this ->fileId );
31+
32+ $ fileId = $ file ->id ;
33+
34+ $ pdfText = app (PdfService::class)->getPdfText ($ file ->path );
2935
3036 $ chunks = $ this ->chuckText ($ pdfText , 1500 , 500 );
3137
@@ -35,20 +41,29 @@ public function handle(): void
3541
3642 $ chunks = array_slice ($ chunks , 0 , 2 );
3743
38- foreach ($ chunks as $ chunk ) {
39- $ jobs [] = new ProcessChunkJob ($ chunk , $ this ->file );
40- }
41-
42- $ jobs [] = new FinalizeFileJob ($ this ->file );
43-
4444 // $this->file->total_chunks = $chuckCount;
4545 /* @phpstan-ignore-next-line */
46- $ this -> file ->total_chunks = 2 ;
47- $ this -> file ->save ();
46+ $ file ->total_chunks = 2 ;
47+ $ file ->save ();
4848
4949 Log::info ("Started processing $ chuckCount chunks " );
5050
51- Bus::chain ($ jobs )->dispatch ();
51+ $ jobs = array_map (
52+ fn ($ chunk ) => new ProcessChunkJob ($ chunk , $ file ->id ),
53+ $ chunks
54+ );
55+
56+ Bus::batch ($ jobs )
57+ ->then (function (Batch $ batch ) use ($ fileId ) {
58+ FinalizeFileJob::dispatch ($ fileId );
59+ })
60+ ->catch (function (Batch $ batch , Throwable $ e ) use ($ fileId ) {
61+ Log::error ("Batch failed for file_id= {$ fileId }: " .$ e ->getMessage ());
62+ })
63+ ->finally (function (Batch $ batch ) use ($ fileId ) {
64+ Log::info ("Batch finished for file_id= {$ fileId }. processed= {$ batch ->processedJobs ()} failed= {$ batch ->failedJobs }" );
65+ })
66+ ->dispatch ();
5267 }
5368
5469 protected function chuckText (
@@ -87,4 +102,19 @@ protected function chuckText(
87102
88103 return $ chunks ;
89104 }
105+
106+ protected function sequenceJobs (): void
107+ {
108+ // foreach ($chunks as $chunk) {
109+ // $jobs[] = new ProcessChunkJob($chunk, $this->file);
110+ // }
111+
112+ // $jobs[] = new FinalizeFileJob($this->file);
113+
114+ // $this->file->total_chunks = $chuckCount;
115+ // $this->file->total_chunks = 2;
116+ // $this->file->save();
117+
118+ // Bus::chain($jobs)->dispatch();
119+ }
90120}
0 commit comments