BaseImportJob.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Jobs;
  3. use Illuminate\Bus\Queueable;
  4. use Illuminate\Contracts\Queue\ShouldQueue;
  5. use Illuminate\Foundation\Bus\Dispatchable;
  6. use Illuminate\Queue\InteractsWithQueue;
  7. use Illuminate\Queue\SerializesModels;
  8. use Illuminate\Support\Facades\Cache;
  9. use Illuminate\Support\Facades\Storage;
  10. use Throwable;
  11. abstract class BaseImportJob implements ShouldQueue
  12. {
  13. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  14. public int $tries = 1;
  15. public int $timeout = 600;
  16. public function __construct(
  17. protected string $filePath,
  18. protected string $importId,
  19. ) {}
  20. public function handle(): void
  21. {
  22. Cache::put($this->importId, ['status' => 'processing'], now()->addDay());
  23. try {
  24. $stats = $this->runSync($this->filePath);
  25. Cache::put($this->importId, [
  26. 'status' => 'completed',
  27. 'stats' => $stats,
  28. ], now()->addDay());
  29. } finally {
  30. $this->cleanupFile();
  31. }
  32. }
  33. public function failed(Throwable $e): void
  34. {
  35. Cache::put($this->importId, [
  36. 'status' => 'failed',
  37. 'message' => $e->getMessage(),
  38. ], now()->addDay());
  39. $this->cleanupFile();
  40. }
  41. abstract protected function runSync(string $filePath): array;
  42. private function cleanupFile(): void
  43. {
  44. Storage::delete($this->filePath);
  45. }
  46. }