From 7994fe0c965b0ab09888526d207752d4a54d055a Mon Sep 17 00:00:00 2001 From: ncoronel Date: Thu, 25 Jun 2026 15:30:11 -0300 Subject: [PATCH] feat(attachments): refactor attachment management to use attachable pivot table and update related models and tests --- .../Models/AttachableAttachment.php | 44 ++++++++++++++++ app/Domains/Attachable/Models/Attachment.php | 11 ++-- .../Models/Concerns/HasAttachments.php | 14 +++-- .../Attachable/Services/AttachmentService.php | 51 ++++++++++++++----- .../Controllers/S3TestController.php | 29 +++++++++-- .../Requests/StoreS3TestFileRequest.php | 2 +- ...factor_attachments_to_attachable_pivot.php | 43 ++++++++++++++++ tests/Feature/Attachable/AttachmentTest.php | 30 +++++++---- 8 files changed, 184 insertions(+), 40 deletions(-) create mode 100644 app/Domains/Attachable/Models/AttachableAttachment.php create mode 100644 database/migrations/2026_06_25_000600_refactor_attachments_to_attachable_pivot.php diff --git a/app/Domains/Attachable/Models/AttachableAttachment.php b/app/Domains/Attachable/Models/AttachableAttachment.php new file mode 100644 index 0000000..caed0da --- /dev/null +++ b/app/Domains/Attachable/Models/AttachableAttachment.php @@ -0,0 +1,44 @@ + 'integer', + 'attachment_id' => 'integer', + ]; + } + + /** + * @return MorphTo + */ + public function attachable(): MorphTo + { + return $this->morphTo(); + } + + /** + * @return BelongsTo + */ + public function attachment(): BelongsTo + { + return $this->belongsTo(Attachment::class, 'attachment_id'); + } +} diff --git a/app/Domains/Attachable/Models/Attachment.php b/app/Domains/Attachable/Models/Attachment.php index ec19376..c94bf4f 100644 --- a/app/Domains/Attachable/Models/Attachment.php +++ b/app/Domains/Attachable/Models/Attachment.php @@ -6,12 +6,10 @@ use App\Domains\Attachable\Enums\AttachmentType; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\MorphTo; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; #[Fillable([ - 'attachable_type', - 'attachable_id', 'key', 'path', 'filename', @@ -38,17 +36,16 @@ class Attachment extends Model protected function casts(): array { return [ - 'attachable_id' => 'integer', 'type' => AttachmentType::class, 'size' => 'integer', ]; } /** - * @return MorphTo + * @return HasMany */ - public function attachable(): MorphTo + public function attachables(): HasMany { - return $this->morphTo(); + return $this->hasMany(AttachableAttachment::class, 'attachment_id'); } } diff --git a/app/Domains/Attachable/Models/Concerns/HasAttachments.php b/app/Domains/Attachable/Models/Concerns/HasAttachments.php index 23d881a..48ec7a4 100644 --- a/app/Domains/Attachable/Models/Concerns/HasAttachments.php +++ b/app/Domains/Attachable/Models/Concerns/HasAttachments.php @@ -4,15 +4,21 @@ namespace App\Domains\Attachable\Models\Concerns; use App\Domains\Attachable\Models\Attachment; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\MorphMany; +use Illuminate\Database\Eloquent\Relations\MorphToMany; trait HasAttachments { /** - * @return MorphMany + * @return MorphToMany */ - public function attachments(): MorphMany + public function attachments(): MorphToMany { - return $this->morphMany(Attachment::class, 'attachable'); + return $this->morphToMany( + Attachment::class, + 'attachable', + 'attachable_attachments', + 'attachable_id', + 'attachment_id', + ); } } diff --git a/app/Domains/Attachable/Services/AttachmentService.php b/app/Domains/Attachable/Services/AttachmentService.php index 62b5651..ba065fd 100644 --- a/app/Domains/Attachable/Services/AttachmentService.php +++ b/app/Domains/Attachable/Services/AttachmentService.php @@ -5,7 +5,6 @@ namespace App\Domains\Attachable\Services; use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Exceptions\AttachmentStorageException; use App\Domains\Attachable\Models\Attachment; -use Illuminate\Database\Eloquent\Model; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; @@ -14,13 +13,9 @@ use Throwable; class AttachmentService { public function store( - Model $attachable, UploadedFile $file, string $path, - AttachmentType $type, ): Attachment { - $this->ensureAttachableExists($attachable); - $normalizedPath = $this->normalizePath($path); if ($normalizedPath === '') { @@ -46,11 +41,11 @@ class AttachmentService try { /** @var Attachment $attachment */ - $attachment = $attachable->attachments()->create([ + $attachment = Attachment::query()->create([ 'key' => $key, 'path' => $storedPath, 'filename' => $filename, - 'type' => $type, + 'type' => $this->resolveAttachmentType($file), 'mime_type' => $file->getClientMimeType() ?? $file->getMimeType() ?? 'application/octet-stream', 'extension' => $file->extension(), 'size' => $file->getSize() ?? 0, @@ -75,13 +70,6 @@ class AttachmentService $attachment->delete(); } - protected function ensureAttachableExists(Model $attachable): void - { - if (! $attachable->exists) { - throw new AttachmentStorageException('Cannot manage attachments for an unsaved model.'); - } - } - protected function normalizePath(string $path): string { return trim($path, '/'); @@ -97,4 +85,39 @@ class AttachmentService return trim($directory, '/'); } + + protected function resolveAttachmentType(UploadedFile $file): AttachmentType + { + $mimeType = strtolower($file->getClientMimeType() ?? $file->getMimeType() ?? ''); + + if (str_starts_with($mimeType, 'image/')) { + return AttachmentType::Image; + } + + if (str_starts_with($mimeType, 'video/')) { + return AttachmentType::Video; + } + + if ($mimeType === 'application/pdf') { + return AttachmentType::Pdf; + } + + if (str_starts_with($mimeType, 'audio/')) { + return AttachmentType::Audio; + } + + if ( + str_starts_with($mimeType, 'text/') + || str_contains($mimeType, 'document') + || str_contains($mimeType, 'word') + || str_contains($mimeType, 'excel') + || str_contains($mimeType, 'spreadsheet') + || str_contains($mimeType, 'presentation') + || str_contains($mimeType, 'officedocument') + ) { + return AttachmentType::Document; + } + + return AttachmentType::Other; + } } diff --git a/app/Domains/StorageTest/Controllers/S3TestController.php b/app/Domains/StorageTest/Controllers/S3TestController.php index 95beb08..ab8f0a9 100644 --- a/app/Domains/StorageTest/Controllers/S3TestController.php +++ b/app/Domains/StorageTest/Controllers/S3TestController.php @@ -2,6 +2,7 @@ namespace App\Domains\StorageTest\Controllers; +use App\Domains\Attachable\Services\AttachmentService; use App\Domains\StorageTest\Requests\GenerateS3TemporaryUrlRequest; use App\Domains\StorageTest\Requests\StoreS3TestFileRequest; use App\Domains\StorageTest\Services\S3TestService; @@ -11,18 +12,36 @@ use Illuminate\Http\JsonResponse; class S3TestController extends Controller { public function __construct( + protected AttachmentService $attachmentService, protected S3TestService $s3TestService, ) { } public function store(StoreS3TestFileRequest $request): JsonResponse { + $attachment = $this->attachmentService->store( + $request->file('file'), + $request->validated('path'), + ); + + $temporaryUrl = $this->s3TestService->generateTemporaryUrl( + $attachment->path, + (int) $request->validated('expires_in_minutes', 10), + ); + return response()->json( - $this->s3TestService->storeTestFile( - $request->file('file'), - $request->validated('directory'), - (int) $request->validated('expires_in_minutes', 10), - ), + [ + 'id' => $attachment->id, + 'key' => $attachment->key, + 'path' => $attachment->path, + 'filename' => $attachment->filename, + 'type' => $attachment->type->value, + 'mime_type' => $attachment->mime_type, + 'extension' => $attachment->extension, + 'size' => $attachment->size, + 'temporary_url' => $temporaryUrl['temporary_url'], + 'temporary_url_expires_at' => $temporaryUrl['temporary_url_expires_at'], + ], 201, ); } diff --git a/app/Domains/StorageTest/Requests/StoreS3TestFileRequest.php b/app/Domains/StorageTest/Requests/StoreS3TestFileRequest.php index 183ca36..bb2df89 100644 --- a/app/Domains/StorageTest/Requests/StoreS3TestFileRequest.php +++ b/app/Domains/StorageTest/Requests/StoreS3TestFileRequest.php @@ -18,7 +18,7 @@ class StoreS3TestFileRequest extends FormRequest { return [ 'file' => ['required', 'file', 'max:10240'], - 'directory' => ['nullable', 'string', 'max:255'], + 'path' => ['required', 'string', 'max:2048'], 'expires_in_minutes' => ['nullable', 'integer', 'min:1', 'max:1440'], ]; } diff --git a/database/migrations/2026_06_25_000600_refactor_attachments_to_attachable_pivot.php b/database/migrations/2026_06_25_000600_refactor_attachments_to_attachable_pivot.php new file mode 100644 index 0000000..1f9f6be --- /dev/null +++ b/database/migrations/2026_06_25_000600_refactor_attachments_to_attachable_pivot.php @@ -0,0 +1,43 @@ +dropIndex(['attachable_type', 'attachable_id']); + $table->dropColumn(['attachable_type', 'attachable_id']); + }); + + Schema::create('attachable_attachments', function (Blueprint $table): void { + $table->id(); + $table->string('attachable_type'); + $table->unsignedBigInteger('attachable_id'); + $table->foreignId('attachment_id')->constrained('attachments')->cascadeOnDelete(); + + $table->unique(['attachable_type', 'attachable_id', 'attachment_id'], 'attachable_attachments_unique'); + $table->index(['attachable_type', 'attachable_id'], 'attachable_attachments_attachable_index'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('attachable_attachments'); + + Schema::table('attachments', function (Blueprint $table): void { + $table->string('attachable_type'); + $table->unsignedBigInteger('attachable_id'); + $table->index(['attachable_type', 'attachable_id']); + }); + } +}; diff --git a/tests/Feature/Attachable/AttachmentTest.php b/tests/Feature/Attachable/AttachmentTest.php index c32c934..f5bf356 100644 --- a/tests/Feature/Attachable/AttachmentTest.php +++ b/tests/Feature/Attachable/AttachmentTest.php @@ -31,11 +31,10 @@ class AttachmentTest extends TestCase $file = UploadedFile::fake()->image('logo.png'); $attachment = app(AttachmentService::class)->store( - $tenant, $file, 'attachments/acme/logo.png', - AttachmentType::Image, ); + $tenant->attachments()->attach($attachment->getKey()); $this->assertSame(AttachmentType::Image, $attachment->type); $this->assertTrue(Str::isUuid($attachment->key)); @@ -44,18 +43,21 @@ class AttachmentTest extends TestCase Storage::disk('s3')->assertExists('attachments/acme/'.$attachment->key); $this->assertDatabaseHas('attachments', [ 'id' => $attachment->id, - 'attachable_type' => $tenant->getMorphClass(), - 'attachable_id' => $tenant->getKey(), 'key' => $attachment->key, 'path' => 'attachments/acme/'.$attachment->key, 'filename' => 'logo.png', 'type' => AttachmentType::Image->value, ]); + $this->assertDatabaseHas('attachable_attachments', [ + 'attachable_type' => $tenant->getMorphClass(), + 'attachable_id' => $tenant->getKey(), + 'attachment_id' => $attachment->id, + ]); $freshAttachment = Attachment::query()->findOrFail($attachment->id); $this->assertSame(AttachmentType::Image, $freshAttachment->type); - $this->assertTrue($freshAttachment->attachable->is($tenant)); + $this->assertTrue($tenant->attachments->contains($freshAttachment)); } public function test_it_does_not_persist_the_attachment_when_the_s3_upload_fails(): void @@ -78,10 +80,8 @@ class AttachmentTest extends TestCase try { app(AttachmentService::class)->store( - $tenant, UploadedFile::fake()->create('manual.pdf', 10, 'application/pdf'), 'attachments/globex/manual.pdf', - AttachmentType::Pdf, ); $this->fail('Expected an AttachmentStorageException to be thrown.'); @@ -102,14 +102,16 @@ class AttachmentTest extends TestCase Storage::disk('s3')->put('attachments/initech/spec.pdf', 'spec'); - $attachment = $tenant->attachments()->create([ + $attachment = Attachment::query()->create([ 'path' => 'attachments/initech/spec.pdf', + 'key' => (string) Str::uuid(), 'filename' => 'spec.pdf', 'type' => AttachmentType::Pdf, 'mime_type' => 'application/pdf', 'extension' => 'pdf', 'size' => 512, ]); + $tenant->attachments()->attach($attachment->getKey()); app(AttachmentService::class)->delete($attachment); @@ -117,6 +119,9 @@ class AttachmentTest extends TestCase $this->assertDatabaseMissing('attachments', [ 'id' => $attachment->id, ]); + $this->assertDatabaseMissing('attachable_attachments', [ + 'attachment_id' => $attachment->id, + ]); } public function test_it_keeps_the_database_record_when_the_s3_delete_fails(): void @@ -127,14 +132,16 @@ class AttachmentTest extends TestCase 'dominio' => 'umbrella.com', ]); - $attachment = $tenant->attachments()->create([ + $attachment = Attachment::query()->create([ 'path' => 'attachments/umbrella/audio.mp3', + 'key' => (string) Str::uuid(), 'filename' => 'audio.mp3', 'type' => AttachmentType::Audio, 'mime_type' => 'audio/mpeg', 'extension' => 'mp3', 'size' => 1024, ]); + $tenant->attachments()->attach($attachment->getKey()); $disk = Mockery::mock(); Storage::shouldReceive('disk') @@ -154,6 +161,11 @@ class AttachmentTest extends TestCase $this->assertDatabaseHas('attachments', [ 'id' => $attachment->id, ]); + $this->assertDatabaseHas('attachable_attachments', [ + 'attachment_id' => $attachment->id, + 'attachable_type' => $tenant->getMorphClass(), + 'attachable_id' => $tenant->getKey(), + ]); } } }