FileService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. * @return File
  32. * @throws Exception
  33. */
  34. public function createZipArchive(string $path, string $archiveName, int $userId = null): File
  35. {
  36. if (!($tempFile = tempnam(sys_get_temp_dir(), Str::random()))) {
  37. throw new Exception('Cant create temporary file!');
  38. }
  39. $zip = new ZipArchive();
  40. $fullPath = storage_path('app/public/' . $path);
  41. $zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
  42. $files = new RecursiveIteratorIterator(
  43. new \RecursiveDirectoryIterator($fullPath),
  44. RecursiveIteratorIterator::LEAVES_ONLY
  45. );
  46. foreach ($files as $file) {
  47. if(!$file->isDir()) {
  48. // Get real and relative path for current file
  49. $filePath = $file->getRealPath();
  50. $relativePath = substr($filePath, strlen($fullPath) + 1);
  51. // Add current file to archive
  52. $zip->addFile($filePath, $relativePath);
  53. }
  54. }
  55. $zip->close();
  56. $fileModel = File::query()->updateOrCreate([
  57. 'link' => url('/storage/') . '/' . Str::replace('/tmp', '', $path) . '/' .$archiveName,
  58. 'path' => $path . '/' .$archiveName,
  59. 'user_id' => $userId ?? auth()->user()->id,
  60. 'original_name' => $archiveName,
  61. 'mime_type' => 'application/zip',
  62. ]);
  63. $contents = file_get_contents($tempFile);
  64. Storage::disk('public')->put($path . '/../' .$archiveName, $contents);
  65. unlink($tempFile);
  66. return $fileModel;
  67. }
  68. }