| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
- namespace App\Services;
- use App\Models\File;
- use Exception;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- use RecursiveIteratorIterator;
- use ZipArchive;
- class FileService
- {
- /**
- * @param $path
- * @param $file
- * @return File
- */
- public function saveUploadedFile($path, $file): File
- {
- Storage::disk('public')->put($path . '/' .$file->getClientOriginalName(), $file->getContent());
- return File::query()->updateOrCreate([
- 'link' => url('/storage/') . '/' . $path . '/' .$file->getClientOriginalName(),
- 'path' => $path . '/' .$file->getClientOriginalName(),
- 'user_id' => auth()->user()->id,
- 'original_name' => $file->getClientOriginalName(),
- 'mime_type' => $file->getClientMimeType(),
- ]);
- }
- /**
- * @param string $path
- * @param string $archiveName
- * @param int|null $userId
- * @param bool $deleteSourceFiles
- * @return File
- * @throws Exception
- */
- public function createZipArchive(string $path, string $archiveName, int $userId = null): File
- {
- if (!($tempFile = tempnam(sys_get_temp_dir(), Str::random()))) {
- throw new Exception('Cant create temporary file!');
- }
- $zip = new ZipArchive();
- $fullPath = storage_path('app/public/' . $path);
- $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
- $files = new RecursiveIteratorIterator(
- new \RecursiveDirectoryIterator($fullPath),
- RecursiveIteratorIterator::LEAVES_ONLY
- );
- foreach ($files as $file) {
- if(!$file->isDir()) {
- // Get real and relative path for current file
- $filePath = $file->getRealPath();
- $relativePath = substr($filePath, strlen($fullPath) + 1);
- // Add current file to archive
- $zip->addFile($filePath, $relativePath);
- }
- }
- $zip->close();
- $fileModel = File::query()->updateOrCreate([
- 'link' => url('/storage/') . '/' . Str::replace('/tmp', '', $path) . '/' .$archiveName,
- 'path' => $path . '/' .$archiveName,
- 'user_id' => $userId ?? auth()->user()->id,
- 'original_name' => $archiveName,
- 'mime_type' => 'application/zip',
- ]);
- $contents = file_get_contents($tempFile);
- Storage::disk('public')->put($path . '/../' .$archiveName, $contents);
- unlink($tempFile);
- return $fileModel;
- }
- }
|