FileService.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Services;
  3. use App\Models\File;
  4. use Exception;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Support\Str;
  7. use RecursiveIteratorIterator;
  8. use ZipArchive;
  9. class FileService
  10. {
  11. /**
  12. * @param $path
  13. * @param $file
  14. * @return File
  15. */
  16. public function saveUploadedFile($path, $file): File
  17. {
  18. Storage::disk('public')->put($path . '/' .$file->getClientOriginalName(), $file->getContent());
  19. return File::query()->updateOrCreate([
  20. 'link' => url('/storage/') . '/' . $path . '/' .$file->getClientOriginalName(),
  21. 'path' => $path . '/' .$file->getClientOriginalName(),
  22. 'user_id' => auth()->user()->id,
  23. 'original_name' => $file->getClientOriginalName(),
  24. 'mime_type' => $file->getClientMimeType(),
  25. ]);
  26. }
  27. /**
  28. * @param string $path
  29. * @param string $archiveName
  30. * @param int|null $userId
  31. * @param bool $deleteSourceFiles
  32. * @return File
  33. * @throws Exception
  34. */
  35. public function createZipArchive(string $path, string $archiveName, int $userId = null): File
  36. {
  37. if (!($tempFile = tempnam(sys_get_temp_dir(), Str::random()))) {
  38. throw new Exception('Cant create temporary file!');
  39. }
  40. $zip = new ZipArchive();
  41. $fullPath = storage_path('app/public/' . $path);
  42. $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  43. $files = new RecursiveIteratorIterator(
  44. new \RecursiveDirectoryIterator($fullPath),
  45. RecursiveIteratorIterator::LEAVES_ONLY
  46. );
  47. foreach ($files as $file) {
  48. if(!$file->isDir()) {
  49. // Get real and relative path for current file
  50. $filePath = $file->getRealPath();
  51. $relativePath = substr($filePath, strlen($fullPath) + 1);
  52. // Add current file to archive
  53. $zip->addFile($filePath, $relativePath);
  54. }
  55. }
  56. $zip->close();
  57. $fileModel = File::query()->updateOrCreate([
  58. 'link' => url('/storage/') . '/' . Str::replace('/tmp', '', $path) . '/' .$archiveName,
  59. 'path' => $path . '/' .$archiveName,
  60. 'user_id' => $userId ?? auth()->user()->id,
  61. 'original_name' => $archiveName,
  62. 'mime_type' => 'application/zip',
  63. ]);
  64. $contents = file_get_contents($tempFile);
  65. Storage::disk('public')->put($path . '/../' .$archiveName, $contents);
  66. unlink($tempFile);
  67. return $fileModel;
  68. }
  69. }