init
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace Lucent\File;
|
||||
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Lucent\LucentException;
|
||||
use Lucent\Record\File;
|
||||
use Lucent\Schema\Schema;
|
||||
use Lucent\Schema\Type;
|
||||
|
||||
class FileService
|
||||
{
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws LucentException
|
||||
*/
|
||||
public static function create(Schema $schema, string $uploadFromUrl, array $file): FileUploadResult
|
||||
{
|
||||
$emptyUploadUrl = empty($uploadFromUrl);
|
||||
$emptyFileData = empty($file);
|
||||
|
||||
if ($schema->type === Type::FILES && $emptyUploadUrl && $emptyFileData) {
|
||||
throw new LucentException("No file data submitted");
|
||||
} elseif ($schema->type !== Type::FILES && !($emptyUploadUrl && $emptyFileData)) {
|
||||
throw new LucentException("You can't upload a file to a regular record");
|
||||
} elseif ($schema->type !== Type::FILES) {
|
||||
return new FileUploadResult(
|
||||
recordFile: null, duplicateId: "", isDuplicate: false
|
||||
);
|
||||
}
|
||||
|
||||
if (!$emptyUploadUrl) {
|
||||
$file = self::uploadFileFromUrl($uploadFromUrl);
|
||||
return uploadFile($schema, $file);
|
||||
}
|
||||
|
||||
return new FileUploadResult(
|
||||
recordFile: File::fromArray($file), duplicateId: "", isDuplicate: false
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws LucentException
|
||||
*/
|
||||
private static function uploadFileFromUrl(string $url): UploadedFile
|
||||
{
|
||||
|
||||
$pathinfo = pathinfo($url);
|
||||
$contents = file_get_contents($url);
|
||||
if ($contents === false) {
|
||||
throw new LucentException("Failed to upload file from url");
|
||||
}
|
||||
$file = '/tmp/' . $pathinfo['basename'];
|
||||
file_put_contents($file, $contents);
|
||||
return new UploadedFile($file, $pathinfo['basename']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user