Igor Morais
Igor Morais

Reputation: 1

Laravel job not creating zip file

I'm using laravel jobs for creating xml files. Those files are created and saved in a folder, and after all the files were created, I want to send those files to a zip and delete the created folder. I'm using laravel 10, and batched jobs to do so. The creation of the files and the creation of the folder works just fine, but when the other job responsible for creating the zip folder and include the xml files into it is called, it appears to work, but the zip folder is not created.

// this is the call for the batched jobs and the CreateExportacaoEsusZip, the job that creates the zip folder
Bus::chain([
                Bus::batch($jobs_batched),
                new CreateExportacaoEsusZip($fold['cryptFolder'], $fold['path'], $file_name),
                function () use ($data, $loteExportacao, $user, $file_name) {
                    $loteExportacao->arquivo = "exportacoes_esus/$file_name.zip";
                    $loteExportacao->em_processamento = false;
                    $loteExportacao->save();

                    $user->notify(new ExportFichasEsusNotification('after', $user));
                    Log::notice(logMessage('Arquivos XML E-sus', 'Geração de Arquivo XML', $user->id));
                }
            ])->catch(function (Batch $batch, Throwable $e) use ($user, $fold) {
                if ($fold['cryptFolder']) {
                    Storage::deleteDirectory("exportacoes_esus/{$fold['cryptFolder']}");
                }

                $user->notify(new ExportFichasEsusNotification('error', $user));
                Log::error(logMessage('Arquivos XML E-sus', 'Geração de Arquivo XML', $user->id), ['error' => $e->getMessage()]);
            })->dispatch();
// The job that creates the zip folder
<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\MountManager;
use ZipArchive;

class CreateExportacaoEsusZip implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private string $folder;
    private string $path;
    private string $file_name;

    /**
     * Create a new job instance.
     */
    public function __construct(string $folder, string $path, string $file_name)
    {
        $this->folder = $folder;
        $this->path = $path;
        $this->file_name = $file_name;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            $zip = new ZipArchive;
            $fileName = storage_path('app/exportacoes_esus') . '/' . $this->file_name . '.zip';

            if (!File::exists($this->path)) {
                throw new \Exception("Directory does not exist: $this->path");
            }

            if ($zip->open($fileName, ZipArchive::CREATE) === true) {
                $files = File::files($this->path);
                if (empty($files)) {
                    throw new \Exception("No files found in directory: $this->path");
                }

                foreach ($files as $value) {
                    $relativeNameInZipFile = basename($value);
                    $zip->addFile($value, $relativeNameInZipFile);
                }

                $zip->close();
                Log::info("ZIP file created successfully: $fileName");
            } else {
                throw new \Exception("Could not create zip file at $fileName");
            }

            if (env('FILESYSTEM_DISK') == 's3') {
                $mountManager = new MountManager([
                    'local' => Storage::disk('local')->getDriver(),
                    's3' => Storage::disk('s3')->getDriver(),
                ]);

                $mountManager->copy("local://exportacoes_esus/$this->file_name.zip", "s3://exportacoes_esus/$this->file_name.zip");
                Storage::disk('local')->delete("exportacoes_esus/$this->file_name.zip");
                Log::info("ZIP file copied to S3 and deleted locally: $this->file_name.zip");
            }

            Storage::disk('local')->deleteDirectory("exportacoes_esus/$this->folder");
            Log::info("Temporary directory deleted: $this->folder");
        } catch (\Exception $e) {
            Log::error('Error creating ZIP file', [
                'folder' => $this->folder,
                'path' => $this->path,
                'file_name' => $this->file_name,
                'error' => $e->getMessage(),
            ]);
            Storage::delete("exportacoes_esus/$this->file_name.zip");
            throw $e;
        }
    }
}

I tried to execute the job without using QUEUE_CONNECTION=database, and it works, so I believe the problem is somewhat related to the execution in background. When I execute it in my local machine, runing windows 11, the zip folder ir created but the files are shown as corrupted. When it is executed in the server, runing in linux, the folder is not created at all. Both of the times there is no error message or warning.

Upvotes: 0

Views: 67

Answers (0)

Related Questions