94 lines
2.8 KiB
PHP
94 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Jobs\ImportTerritoryPdfFolder;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Str;
|
|
use RuntimeException;
|
|
use ZipArchive;
|
|
|
|
class TerritorioPdfImportDispatcher
|
|
{
|
|
public function __construct(
|
|
protected TerritorioPdfImportState $stateService,
|
|
) {
|
|
}
|
|
|
|
public function dispatchStoredFiles(string $importId, array $storedFiles, ?int $actorId, string $initialLog): array
|
|
{
|
|
$state = $this->stateService->initialize($importId, count($storedFiles));
|
|
$this->stateService->appendLog($importId, $initialLog);
|
|
|
|
ImportTerritoryPdfFolder::dispatch($importId, $storedFiles, $actorId);
|
|
|
|
return $this->stateService->get($importId) ?? $state;
|
|
}
|
|
|
|
public function dispatchUploadedZip(UploadedFile $zipFile, ?int $actorId): string
|
|
{
|
|
$importId = (string) Str::uuid();
|
|
$zipStoredPath = $zipFile->storeAs(
|
|
'bulk-territori-imports/' . $importId,
|
|
'archivio-' . $importId . '.zip',
|
|
'local'
|
|
);
|
|
|
|
$zipAbsolutePath = storage_path('app/' . $zipStoredPath);
|
|
$zip = new ZipArchive();
|
|
|
|
if ($zip->open($zipAbsolutePath) !== true) {
|
|
throw new RuntimeException('Impossibile aprire il file ZIP.');
|
|
}
|
|
|
|
$storedFiles = [];
|
|
$entryIndex = 0;
|
|
|
|
try {
|
|
for ($index = 0; $index < $zip->numFiles; $index++) {
|
|
$entryName = $zip->getNameIndex($index);
|
|
|
|
if (! $entryName || str_ends_with($entryName, '/')) {
|
|
continue;
|
|
}
|
|
|
|
if (strtolower(pathinfo($entryName, PATHINFO_EXTENSION)) !== 'pdf') {
|
|
continue;
|
|
}
|
|
|
|
$content = $zip->getFromIndex($index);
|
|
if ($content === false) {
|
|
continue;
|
|
}
|
|
|
|
$originalName = basename($entryName);
|
|
$safeName = Str::slug(pathinfo($originalName, PATHINFO_FILENAME));
|
|
$storedPath = 'bulk-territori-imports/' . $importId . '/zip-' . str_pad((string) $entryIndex, 4, '0', STR_PAD_LEFT) . '-' . $safeName . '.pdf';
|
|
|
|
file_put_contents(storage_path('app/' . $storedPath), $content);
|
|
|
|
$storedFiles[] = [
|
|
'original_name' => $originalName,
|
|
'stored_path' => $storedPath,
|
|
];
|
|
|
|
$entryIndex++;
|
|
}
|
|
} finally {
|
|
$zip->close();
|
|
}
|
|
|
|
if ($storedFiles === []) {
|
|
throw new RuntimeException('Lo ZIP non contiene file PDF validi.');
|
|
}
|
|
|
|
$this->dispatchStoredFiles(
|
|
$importId,
|
|
$storedFiles,
|
|
$actorId,
|
|
'Archivio ZIP ricevuto: ' . count($storedFiles) . ' PDF estratti e messi in coda per l\'elaborazione.'
|
|
);
|
|
|
|
return $importId;
|
|
}
|
|
} |