Feat: Create a Service for Download Proof and make it reusable

This commit is contained in:
Sallu9007
2025-05-11 15:41:58 +05:30
parent c224497740
commit 6e634eda5a
4 changed files with 141 additions and 58 deletions

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Storage;
use ZipArchive;
class ProofDownloadService
{
public function downloadProofs($model, $ids, $filePathColumn = 'proof')
{
// Validate IDs
if (empty($ids)) {
return [
'error' => 'No items selected',
];
}
// Fetch records with proofs
$responses = $model::whereIn('id', $ids)
->whereNotNull($filePathColumn)
->get();
if ($responses->isEmpty()) {
return [
'error' => 'No valid proofs found',
];
}
// Create a temporary zip file
$zipFileName = 'proofs_' . time() . '.zip';
$zipFilePath = storage_path('app/public/temp/' . $zipFileName);
// Ensure the temp directory exists
if (!Storage::disk('public')->exists('temp')) {
Storage::disk('public')->makeDirectory('temp');
}
$zip = new ZipArchive();
if ($zip->open($zipFilePath, ZipArchive::CREATE) !== true) {
return [
'error' => 'Could not create zip file',
];
}
$fileCount = 0;
foreach ($responses as $response) {
if (Storage::disk('public')->exists($response->$filePathColumn)) {
$fileContent = Storage::disk('public')->get($response->$filePathColumn);
// Get original filename from path
$originalName = basename($response->$filePathColumn);
// Add file to the zip with a prefix to avoid duplicate names
$fileNameInZip = $response->id . '_' . $originalName;
$zip->addFromString($fileNameInZip, $fileContent);
$fileCount++;
}
}
$zip->close();
if ($fileCount === 0) {
// Delete the empty zip file
if (file_exists($zipFilePath)) {
unlink($zipFilePath);
}
return [
'error' => 'No files found to download',
];
}
return [
'success' => true,
'filePath' => $zipFilePath,
'fileName' => $zipFileName,
];
}
}