moved move_to_external_storage into HelperService.php

This commit is contained in:
Peter Papp
2021-03-14 13:05:53 +01:00
parent 9cc9111d63
commit 419a1d8180
2 changed files with 70 additions and 66 deletions

View File

@@ -3,9 +3,13 @@
namespace App\Services;
use App\Models\Folder;
use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use DB;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpKernel\Exception\HttpException;
class HelperService
{
@@ -88,4 +92,69 @@ class HelperService
abort(423, 'You exceed your storage limit!');
}
}
/**
* Move file to external storage if is set
*
* @param string $filename
* @param string|null $thumbnail
*/
function move_to_external_storage(string $filename, ?string $thumbnail): void
{
$disk_local = Storage::disk('local');
foreach ([$filename, $thumbnail] as $file) {
// Check if file exist
if (!$file) continue;
// Get file size
$filesize = $disk_local->size('files/' . $file);
// If file is bigger than 5.2MB then run multipart upload
if ($filesize > 5242880) {
// Get driver
$driver = \Storage::getDriver();
// Get adapter
$adapter = $driver->getAdapter();
// Get client
$client = $adapter->getClient();
// Prepare the upload parameters.
// TODO: replace local files with temp folder
$uploader = new MultipartUploader($client, config('filesystems.disks.local.root') . '/files/' . $file, [
'bucket' => $adapter->getBucket(),
'key' => 'files/' . $file
]);
try {
// Upload content
$uploader->upload();
} catch (MultipartUploadException $e) {
// Write error log
Log::error($e->getMessage());
// Delete file after error
$disk_local->delete('files/' . $file);
throw new HttpException(409, $e->getMessage());
}
} else {
// Stream file object to s3
// TODO: replace local files with temp folder
Storage::putFileAs('files', config('filesystems.disks.local.root') . '/files/' . $file, $file, 'private');
}
// Delete file after upload
$disk_local->delete('files/' . $file);
}
}
}