2023-10-02 23:10:49 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace Lucent\File;
|
|
|
|
|
|
|
|
|
|
use Illuminate\Http\UploadedFile;
|
2023-10-04 13:32:30 +03:00
|
|
|
use Lucent\Channel\ChannelService;
|
2023-10-02 23:10:49 +03:00
|
|
|
use Lucent\LucentException;
|
|
|
|
|
use Lucent\Record\File;
|
2023-10-04 13:32:30 +03:00
|
|
|
use Lucent\Record\QueryRecord;
|
2023-10-02 23:10:49 +03:00
|
|
|
use Lucent\Schema\Schema;
|
|
|
|
|
use Lucent\Schema\Type;
|
|
|
|
|
|
|
|
|
|
class FileService
|
|
|
|
|
{
|
|
|
|
|
|
2023-10-04 13:32:30 +03:00
|
|
|
public function __construct(
|
|
|
|
|
public ChannelService $channelService
|
|
|
|
|
)
|
2023-10-02 23:10:49 +03:00
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-04 13:32:30 +03:00
|
|
|
public function getPath(QueryRecord $file): string
|
|
|
|
|
{
|
|
|
|
|
return $this->channelService->channel->url. "/storage/".$file->_file->path;
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-02 23:10:49 +03:00
|
|
|
/**
|
|
|
|
|
* @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']);
|
|
|
|
|
}
|
|
|
|
|
}
|