123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- <?php
- namespace App\Services\File\Upload;
- use App\Models\Folder;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Auth;
- class KeepDirectoryUploadService
- {
- use FilesUploadTrait;
- protected array $objectWhere = [];
- protected ?Folder $parentFolder = null;
- protected int $filesSize = 0;
- public function __construct(protected Request $request)
- {
- $this->checkFormData();
- $this->objectWhere = [
- 'object_id' => $this->request->get("object_id", 0),
- 'object_type' => $this->request->get("object_type"),
- ];
- $this->parentFolder = $this->request->get("folder_id")
- ? Folder::query()->where($this->objectWhere)->findOrFail($this->request->get("folder_id"))
- : null;
- }
- public function upload(): array
- {
- $folderRelations = $this->buildFolder();
- $items = [];
- $fileNames = $this->request->get("file_names", []);
- foreach ($this->request->file("files") as $index => $file) {
- $item = $this->uploadFile($this->request, $file);
- $item['file']['folder_id'] = $folderRelations[$index] ?? 0;
- $item['file']['title'] = $fileNames[$index] ?? $item['file']['title'];
- $items[] = $item;
- }
- $uploadedFiles = $this->storeFiles($items);
- $this->updateUsedStorageCapacity($this->filesSize);
- return $uploadedFiles;
- }
- protected function buildFolder(): array
- {
- $folderRelations = [];
- $uuid = $this->request->get("uuid");
- foreach ($this->request->folders as $index => $folder) {
- $parentFolder = $this->parentFolder;
- $folderPathArr = array_filter(explode('/', $folder));
- if (! $folderPathArr) {
- $folderRelations[$index] = $parentFolder?->id ?? 0;
- }
- foreach ($folderPathArr as $folderName) {
- $parentId = $parentFolder?->id ?? 0;
- $folder = Folder::query()
- ->where($this->objectWhere)
- ->where("name", $folderName)
- ->when($uuid, fn($query) => $query->where("uuid", $uuid))
- ->where("parent_id", $parentId)
- ->first();
- if (! $folder) {
- $folder = Folder::query()->create([
- 'company_id' => Auth::user()->company_id,
- ...$this->objectWhere,
- 'uuid' => $uuid,
- 'parent_id' => $parentId,
- 'name' => $folderName
- ]);
- $folder->path = $parentFolder ? $parentFolder?->path . $folder->id . "," : sprintf(",%s,", $folder->id);
- $folder->save();
- }
- $parentFolder = $folder;
- $folderRelations[$index] = $folder->id;
- }
- }
- return $folderRelations;
- }
- protected function checkFormData()
- {
- throw_validation_if(
- count($this->request->file("files")) != count($this->request->folders),
- "File and directory do not match"
- );
- $this->filesSize = $this->checkRequestData($this->request);
- }
- }
|