Files
Ilya Rogozhin 459d048596 Speed up export
2026-06-10 10:31:13 +02:00

74 lines
2.3 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\User;
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\Cache;
use Illuminate\Support\Facades\File;
use Throwable;
class UsersExport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Execute the job.
*/
public function handle(): void
{
try {
$exportPath = public_path('exports');
if (!File::isDirectory($exportPath)) {
File::makeDirectory($exportPath, 0755, true);
}
$oldFiles = File::glob($exportPath . '/users_export_*.csv');
foreach ($oldFiles as $file) {
File::delete($file);
}
$filename = 'users_export_' . now()->format('Y-m-d_H-i-s') . '.csv';
$filePath = $exportPath . '/' . $filename;
$fileHandle = fopen($filePath, 'w');
fputcsv($fileHandle, ['Имя', 'Фамилия', 'Телефон', 'E-mail']);
User::select('id', 'name', 'surname', 'phone_number', 'email')
->chunkById(30000, function ($users) use ($fileHandle) {
$chunkHandle = fopen('php://memory', 'r+');
foreach ($users as $user) {
fputcsv($chunkHandle, [
$user->name,
$user->surname,
$user->phone_number,
$user->email,
]);
}
rewind($chunkHandle);
$csvData = stream_get_contents($chunkHandle);
fclose($chunkHandle);
fwrite($fileHandle, $csvData);
});
fclose($fileHandle);
Cache::forever('export_status', 'standby');
Cache::forever('last_export_file', 'exports/' . $filename);
} catch (Throwable $e) {
Cache::forever('export_status', 'failed');
report($e);
throw $e;
}
}
}