FileAssociationService.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Services\File;
  3. use App\Models\Enums\FileObjectType;
  4. use App\Models\Enums\FileSource;
  5. use App\Models\File;
  6. use Carbon\Carbon;
  7. use Illuminate\Support\Collection;
  8. use Illuminate\Support\Facades\Auth;
  9. class FileAssociationService
  10. {
  11. protected array $fileIds = [];
  12. protected ?Collection $files = null;
  13. protected ?FileObjectType $fileObjectType = null;
  14. public function check(array $fileIds, FileObjectType $fileObjectType, string $fileUUID = null)
  15. {
  16. if (! $fileIds) {
  17. return;
  18. }
  19. $this->fileIds = $fileIds;
  20. $this->fileObjectType = $fileObjectType;
  21. $this->files = File::query()
  22. ->with(['folder'])
  23. ->whereIn("id", $fileIds)
  24. ->where("created_by", Auth::id())
  25. ->whereNull("object_id")
  26. ->where("object_type", $fileObjectType->value)
  27. ->where("created_at", ">=", Carbon::now()->subHours(3))
  28. ->orderBy("created_at")
  29. ->get();
  30. foreach ($this->files as $file) {
  31. if (! $file->folder_id) {
  32. continue;
  33. }
  34. throw_validation_if($fileUUID != $file->folder->uuid, "illegal uuid");
  35. throw_validation_if($file->folder->object_id, "The folder has been associated and cannot be associated again");
  36. }
  37. }
  38. public function association(string $objectId,)
  39. {
  40. if (! $this->files) {
  41. return;
  42. }
  43. foreach ($this->files as $file) {
  44. if ($file->source == FileSource::ATTACHMENT->value) {
  45. $version = File::query()
  46. ->where("created_by", Auth::id())
  47. ->where("object_id", $objectId)
  48. ->where("object_type", $this->fileObjectType->value)
  49. ->where("title", $file->title)
  50. ->where("folder_id", $file->folder_id)
  51. ->count();
  52. $file->version = $version + 1;
  53. }
  54. $file->object_id = $objectId;
  55. $file->save();
  56. if ($file->folder) {
  57. $file->folder->object_id = $objectId;
  58. $file->folder->save();
  59. }
  60. }
  61. }
  62. }