| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?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
- * @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) {
- $filePath = $file->getRealPath();
- $relativePath = substr($filePath, strlen($fullPath) + 1);
- if(!$file->isDir()) {
- $zip->addFile($filePath, $relativePath);
- } else {
- $zip->addEmptyDir($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;
- }
- }
|