FileService.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. $filePath = $file->getRealPath();
  48. $relativePath = substr($filePath, strlen($fullPath) + 1);
  49. if(!$file->isDir()) {
  50. $zip->addFile($filePath, $relativePath);
  51. } else {
  52. $zip->addEmptyDir($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. }