1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace App\Services\File;
- use App\Models\Enums\FileObjectType;
- use App\Models\Enums\FileSource;
- use App\Models\File;
- use Carbon\Carbon;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\Auth;
- class FileAssociationService
- {
- protected array $fileIds = [];
- protected ?Collection $files = null;
- protected ?FileObjectType $fileObjectType = null;
- public function check(array $fileIds, FileObjectType $fileObjectType, string $fileUUID = null)
- {
- if (! $fileIds) {
- return;
- }
- $this->fileIds = $fileIds;
- $this->fileObjectType = $fileObjectType;
- $this->files = File::query()
- ->with(['folder'])
- ->whereIn("id", $fileIds)
- ->where("created_by", Auth::id())
- ->whereNull("object_id")
- ->where("object_type", $fileObjectType->value)
- ->where("created_at", ">=", Carbon::now()->subHours(3))
- ->orderBy("created_at")
- ->get();
- foreach ($this->files as $file) {
- if (! $file->folder_id) {
- continue;
- }
- throw_validation_if($fileUUID != $file->folder->uuid, "illegal uuid");
- throw_validation_if($file->folder->object_id, "The folder has been associated and cannot be associated again");
- }
- }
- public function association(string $objectId,)
- {
- if (! $this->files) {
- return;
- }
- foreach ($this->files as $file) {
- if ($file->source == FileSource::ATTACHMENT->value) {
- $version = File::query()
- ->where("created_by", Auth::id())
- ->where("object_id", $objectId)
- ->where("object_type", $this->fileObjectType->value)
- ->where("title", $file->title)
- ->where("folder_id", $file->folder_id)
- ->count();
- $file->version = $version + 1;
- }
- $file->object_id = $objectId;
- $file->save();
- if ($file->folder) {
- $file->folder->object_id = $objectId;
- $file->folder->save();
- }
- }
- }
- }
|