2018-04-03 00:04:32 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Services;
|
|
|
|
|
2019-07-16 03:44:31 +08:00
|
|
|
use App\Contracts\Service;
|
2018-04-03 06:34:58 +08:00
|
|
|
use App\Models\File;
|
2019-08-27 02:43:50 +08:00
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
use Illuminate\Support\Str;
|
2018-04-03 00:04:32 +08:00
|
|
|
|
|
|
|
class FileService extends Service
|
|
|
|
{
|
|
|
|
/**
|
2018-04-03 06:34:58 +08:00
|
|
|
* Save a file to disk and return a File asset
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-04-03 00:04:32 +08:00
|
|
|
* @param \Illuminate\Http\UploadedFile $file
|
|
|
|
* @param string $folder
|
2018-04-03 06:34:58 +08:00
|
|
|
* @param array $attrs
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
2018-04-03 06:34:58 +08:00
|
|
|
* @throws \Hashids\HashidsException
|
2018-08-27 00:40:04 +08:00
|
|
|
*
|
|
|
|
* @return File
|
2018-04-03 00:04:32 +08:00
|
|
|
*/
|
2018-04-03 06:34:58 +08:00
|
|
|
public function saveFile($file, $folder, array $attrs)
|
2018-04-03 00:04:32 +08:00
|
|
|
{
|
2018-04-03 06:34:58 +08:00
|
|
|
$attrs = array_merge([
|
|
|
|
'name' => '',
|
|
|
|
'description' => '',
|
|
|
|
'public' => false,
|
|
|
|
'ref_model' => '',
|
|
|
|
'ref_model_id' => '',
|
|
|
|
'disk' => config('filesystems.public_files'),
|
|
|
|
], $attrs);
|
2018-04-03 00:04:32 +08:00
|
|
|
|
2018-04-03 06:34:58 +08:00
|
|
|
$id = File::createNewHashId();
|
2018-04-03 00:04:32 +08:00
|
|
|
$path_info = pathinfo($file->getClientOriginalName());
|
2018-04-03 06:34:58 +08:00
|
|
|
|
2018-08-27 00:40:04 +08:00
|
|
|
// Create the file, add the ID to the front of the file to account
|
|
|
|
// for any duplicate filenames, but still can be found in an `ls`
|
2019-08-27 02:43:50 +08:00
|
|
|
$filename = $id.'_'.str_slug(trim($path_info['filename'])).'.'.$path_info['extension'];
|
2018-04-03 06:34:58 +08:00
|
|
|
$file_path = $file->storeAs($folder, $filename, $attrs['disk']);
|
|
|
|
|
2019-08-27 02:43:50 +08:00
|
|
|
Log::info('File saved to '.$file_path);
|
|
|
|
|
2018-04-03 06:34:58 +08:00
|
|
|
$asset = new File($attrs);
|
|
|
|
$asset->id = $id;
|
|
|
|
$asset->path = $file_path;
|
|
|
|
$asset->save();
|
|
|
|
|
|
|
|
return $asset;
|
2018-04-03 00:04:32 +08:00
|
|
|
}
|
2019-08-27 02:43:50 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove a file, if it exists on disk
|
|
|
|
*
|
|
|
|
* @param File $file
|
|
|
|
*
|
|
|
|
* @throws \Exception
|
|
|
|
*/
|
|
|
|
public function removeFile($file)
|
|
|
|
{
|
|
|
|
if (!Str::startsWith($file->path, 'http')) {
|
|
|
|
Storage::disk(config('filesystems.public_files'))
|
|
|
|
->delete($file->path);
|
|
|
|
}
|
|
|
|
|
|
|
|
$file->delete();
|
|
|
|
}
|
2018-04-03 00:04:32 +08:00
|
|
|
}
|