91 lines
2.5 KiB
PHP
91 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use Illuminate\Http\File;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Arr;
|
|
use Illuminate\Support\Facades\App;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Str;
|
|
|
|
trait VideoFileHelper
|
|
{
|
|
use MimeToExtensionHelper;
|
|
|
|
public $public_path = "/public/uploads/";
|
|
public $storage_path = "/storage/uploads/";
|
|
|
|
public function uploadVideoFile($file, $prefix, bool $isEncoded): string
|
|
{
|
|
if ($isEncoded) {
|
|
$file = $this->create_video_file_from_base64($file);
|
|
}
|
|
$videoPath = '';
|
|
if ($file) {
|
|
$extension = $file->getClientOriginalExtension();
|
|
$fileName = $prefix . '_' . Str::random(30) . '.' . $extension;
|
|
$url = $file->storeAs($this->public_path, $fileName);
|
|
$publicPath = public_path($this->storage_path . $fileName);
|
|
|
|
|
|
$videoPath = preg_replace("/public/", "", $url);
|
|
}
|
|
return $videoPath;
|
|
}
|
|
|
|
public function create_video_file_from_base64($base64File) : UploadedFile
|
|
{
|
|
$fileData = base64_decode(Arr::last(explode(',', $base64File)));
|
|
|
|
//Get MimeType
|
|
$fileInfo = finfo_open();
|
|
$mimeType = finfo_buffer($fileInfo, $fileData, FILEINFO_MIME_TYPE);
|
|
|
|
//Get Extension from MimeType
|
|
$ext = $this->mime2ext($mimeType);
|
|
|
|
// save it to temporary dir first.
|
|
$tempFilePath = sys_get_temp_dir() . '/' . Str::uuid()->toString() . '.' . $ext;
|
|
|
|
file_put_contents($tempFilePath, $fileData);
|
|
|
|
$tempFileObject = new File($tempFilePath);
|
|
return new UploadedFile(
|
|
$tempFileObject->getPathname(),
|
|
$tempFileObject->getFilename(),
|
|
$tempFileObject->getMimeType(),
|
|
0,
|
|
true
|
|
);
|
|
}
|
|
|
|
public function getVideoFileFullUrl($file) : NULL|string
|
|
{
|
|
if($file){
|
|
return App::make('url')->to('/') . '/storage' . $file;
|
|
}
|
|
return NULL;
|
|
|
|
}
|
|
|
|
public function updateVideoFile($file, $existingFile, $prefix, bool $isEncoded): bool|string
|
|
{
|
|
$isDeleted = $this->deleteVideoFile($existingFile);
|
|
if($isDeleted) {
|
|
return $this->uploadVideoFile($file, $prefix, $isEncoded);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public function deleteVideoFile($file) : bool {
|
|
$file = 'storage' . $file;
|
|
if(file_exists($file)) {
|
|
unlink($file);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
}
|