FileService.php 2.8 KB

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