fileObjectType = FileObjectType::from($request->object_type); if ($request->object_id) { $this->object = $this->fileObjectType->modelBuilderAllowed($request->object_id)->findOrFail($request->object_id); } $filesSize = 0; foreach ($request->file("files") as $file) { throw_validation_if(! $file->isValid(), "File upload failed."); $filesSize += $file->getSize(); } throw_validation_if( $filesSize + Auth::user()->company->used_storage_capacity > Auth::user()->company->storage_size, "Storage capacity is insufficient, please contact the administrator." ); return $filesSize; } protected function uploadFile(Request $request, UploadedFile $file): array { $pathname = $file->storeAs( sprintf("c%s/%s/%s", Auth::user()->company_id, $request->get("object_type"), date("Ymd")), sprintf("%s.%s", md5(uniqid()), $file->extension()) ); throw_validation_if(! $pathname, "File upload failed."); return [ 'pathname' => $pathname, 'title' => $file->getClientOriginalName(), 'size' => $file->getSize(), 'extension' => $file->extension(), 'object_type' => $request->object_type, 'object_id' => $request->object_id, 'created_by' => Auth::id(), 'company_id' => Auth::user()->company_id, 'source' => $request->get("source", 1), 'uuid' => $request->get("uuid"), ]; } protected function storeFiles(array $items) { $uploadedFiles = []; foreach ($items as $item) { if ($item['object_id'] && $item['source'] == 1||$item['uuid'] && $item['source']== 1) { $version = File::query() ->where('object_type', $item['object_type']) ->where('object_id', $item['object_id']) ->where("title", $item['title']) ->where("source", 1) ->where("folder_id", $item['folder_id'] ?? 0) ->count(); $item['version'] = $version + 1; $item['is_latest_version'] = 1; File::query() ->where('object_type', $item['object_type']) ->where('object_id', $item['object_id']) ->where("title", $item['title']) ->where("folder_id", $item['folder_id'] ?? 0) ->where("source", 1) ->where("is_latest_version", 1) ->update([ 'is_latest_version' => 0 ]); } $file = File::query()->create($item); $uploadedFiles[] = new FileUploadSuccessResource($file); } $this->updateObjectVersion(); return $uploadedFiles; } protected function updateObjectVersion() { if (!$this->object) { return; } if ($this->fileObjectType == FileObjectType::CONTAINER) { $version = $this->object->version; $this->object->version++; $this->object->save(); $fileIds = File::query()->where([ 'object_type' => $this->fileObjectType->value, 'object_id' => $this->object->id ])->pluck("id"); ContainerContent::query()->create([ ...$this->object->content($version)->first()->toArray(), 'created_by' => Auth::id(), 'files' => $fileIds->join(","), 'version' => $this->object->version, ]); } } protected function updateUsedStorageCapacity(int $filesSize) { $company = Auth::user()->company; $company->increment("used_storage_capacity", $filesSize); $company->save(); } }