feat(attachments): refactor attachment management to use attachable pivot table and update related models and tests

This commit is contained in:
2026-06-25 15:30:11 -03:00
parent ee59236d55
commit 7994fe0c96
8 changed files with 184 additions and 40 deletions

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Domains\Attachable\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
#[Fillable([
'attachable_type',
'attachable_id',
'attachment_id',
])]
class AttachableAttachment extends Model
{
protected $table = 'attachable_attachments';
public $timestamps = false;
protected function casts(): array
{
return [
'attachable_id' => 'integer',
'attachment_id' => 'integer',
];
}
/**
* @return MorphTo<Model, $this>
*/
public function attachable(): MorphTo
{
return $this->morphTo();
}
/**
* @return BelongsTo<Attachment, $this>
*/
public function attachment(): BelongsTo
{
return $this->belongsTo(Attachment::class, 'attachment_id');
}
}

View File

@@ -6,12 +6,10 @@ use App\Domains\Attachable\Enums\AttachmentType;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str; use Illuminate\Support\Str;
#[Fillable([ #[Fillable([
'attachable_type',
'attachable_id',
'key', 'key',
'path', 'path',
'filename', 'filename',
@@ -38,17 +36,16 @@ class Attachment extends Model
protected function casts(): array protected function casts(): array
{ {
return [ return [
'attachable_id' => 'integer',
'type' => AttachmentType::class, 'type' => AttachmentType::class,
'size' => 'integer', 'size' => 'integer',
]; ];
} }
/** /**
* @return MorphTo<Model, $this> * @return HasMany<AttachableAttachment, $this>
*/ */
public function attachable(): MorphTo public function attachables(): HasMany
{ {
return $this->morphTo(); return $this->hasMany(AttachableAttachment::class, 'attachment_id');
} }
} }

View File

@@ -4,15 +4,21 @@ namespace App\Domains\Attachable\Models\Concerns;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphToMany;
trait HasAttachments trait HasAttachments
{ {
/** /**
* @return MorphMany<Attachment, Model> * @return MorphToMany<Attachment, Model, $this>
*/ */
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',
);
} }
} }

View File

@@ -5,7 +5,6 @@ namespace App\Domains\Attachable\Services;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException; use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -14,13 +13,9 @@ use Throwable;
class AttachmentService class AttachmentService
{ {
public function store( public function store(
Model $attachable,
UploadedFile $file, UploadedFile $file,
string $path, string $path,
AttachmentType $type,
): Attachment { ): Attachment {
$this->ensureAttachableExists($attachable);
$normalizedPath = $this->normalizePath($path); $normalizedPath = $this->normalizePath($path);
if ($normalizedPath === '') { if ($normalizedPath === '') {
@@ -46,11 +41,11 @@ class AttachmentService
try { try {
/** @var Attachment $attachment */ /** @var Attachment $attachment */
$attachment = $attachable->attachments()->create([ $attachment = Attachment::query()->create([
'key' => $key, 'key' => $key,
'path' => $storedPath, 'path' => $storedPath,
'filename' => $filename, 'filename' => $filename,
'type' => $type, 'type' => $this->resolveAttachmentType($file),
'mime_type' => $file->getClientMimeType() ?? $file->getMimeType() ?? 'application/octet-stream', 'mime_type' => $file->getClientMimeType() ?? $file->getMimeType() ?? 'application/octet-stream',
'extension' => $file->extension(), 'extension' => $file->extension(),
'size' => $file->getSize() ?? 0, 'size' => $file->getSize() ?? 0,
@@ -75,13 +70,6 @@ class AttachmentService
$attachment->delete(); $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 protected function normalizePath(string $path): string
{ {
return trim($path, '/'); return trim($path, '/');
@@ -97,4 +85,39 @@ class AttachmentService
return trim($directory, '/'); 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;
}
} }

View File

@@ -2,6 +2,7 @@
namespace App\Domains\StorageTest\Controllers; namespace App\Domains\StorageTest\Controllers;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\StorageTest\Requests\GenerateS3TemporaryUrlRequest; use App\Domains\StorageTest\Requests\GenerateS3TemporaryUrlRequest;
use App\Domains\StorageTest\Requests\StoreS3TestFileRequest; use App\Domains\StorageTest\Requests\StoreS3TestFileRequest;
use App\Domains\StorageTest\Services\S3TestService; use App\Domains\StorageTest\Services\S3TestService;
@@ -11,18 +12,36 @@ use Illuminate\Http\JsonResponse;
class S3TestController extends Controller class S3TestController extends Controller
{ {
public function __construct( public function __construct(
protected AttachmentService $attachmentService,
protected S3TestService $s3TestService, protected S3TestService $s3TestService,
) { ) {
} }
public function store(StoreS3TestFileRequest $request): JsonResponse 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( return response()->json(
$this->s3TestService->storeTestFile( [
$request->file('file'), 'id' => $attachment->id,
$request->validated('directory'), 'key' => $attachment->key,
(int) $request->validated('expires_in_minutes', 10), '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, 201,
); );
} }

View File

@@ -18,7 +18,7 @@ class StoreS3TestFileRequest extends FormRequest
{ {
return [ return [
'file' => ['required', 'file', 'max:10240'], 'file' => ['required', 'file', 'max:10240'],
'directory' => ['nullable', 'string', 'max:255'], 'path' => ['required', 'string', 'max:2048'],
'expires_in_minutes' => ['nullable', 'integer', 'min:1', 'max:1440'], 'expires_in_minutes' => ['nullable', 'integer', 'min:1', 'max:1440'],
]; ];
} }

View File

@@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('attachments', function (Blueprint $table): void {
$table->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']);
});
}
};

View File

@@ -31,11 +31,10 @@ class AttachmentTest extends TestCase
$file = UploadedFile::fake()->image('logo.png'); $file = UploadedFile::fake()->image('logo.png');
$attachment = app(AttachmentService::class)->store( $attachment = app(AttachmentService::class)->store(
$tenant,
$file, $file,
'attachments/acme/logo.png', 'attachments/acme/logo.png',
AttachmentType::Image,
); );
$tenant->attachments()->attach($attachment->getKey());
$this->assertSame(AttachmentType::Image, $attachment->type); $this->assertSame(AttachmentType::Image, $attachment->type);
$this->assertTrue(Str::isUuid($attachment->key)); $this->assertTrue(Str::isUuid($attachment->key));
@@ -44,18 +43,21 @@ class AttachmentTest extends TestCase
Storage::disk('s3')->assertExists('attachments/acme/'.$attachment->key); Storage::disk('s3')->assertExists('attachments/acme/'.$attachment->key);
$this->assertDatabaseHas('attachments', [ $this->assertDatabaseHas('attachments', [
'id' => $attachment->id, 'id' => $attachment->id,
'attachable_type' => $tenant->getMorphClass(),
'attachable_id' => $tenant->getKey(),
'key' => $attachment->key, 'key' => $attachment->key,
'path' => 'attachments/acme/'.$attachment->key, 'path' => 'attachments/acme/'.$attachment->key,
'filename' => 'logo.png', 'filename' => 'logo.png',
'type' => AttachmentType::Image->value, '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); $freshAttachment = Attachment::query()->findOrFail($attachment->id);
$this->assertSame(AttachmentType::Image, $freshAttachment->type); $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 public function test_it_does_not_persist_the_attachment_when_the_s3_upload_fails(): void
@@ -78,10 +80,8 @@ class AttachmentTest extends TestCase
try { try {
app(AttachmentService::class)->store( app(AttachmentService::class)->store(
$tenant,
UploadedFile::fake()->create('manual.pdf', 10, 'application/pdf'), UploadedFile::fake()->create('manual.pdf', 10, 'application/pdf'),
'attachments/globex/manual.pdf', 'attachments/globex/manual.pdf',
AttachmentType::Pdf,
); );
$this->fail('Expected an AttachmentStorageException to be thrown.'); $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'); Storage::disk('s3')->put('attachments/initech/spec.pdf', 'spec');
$attachment = $tenant->attachments()->create([ $attachment = Attachment::query()->create([
'path' => 'attachments/initech/spec.pdf', 'path' => 'attachments/initech/spec.pdf',
'key' => (string) Str::uuid(),
'filename' => 'spec.pdf', 'filename' => 'spec.pdf',
'type' => AttachmentType::Pdf, 'type' => AttachmentType::Pdf,
'mime_type' => 'application/pdf', 'mime_type' => 'application/pdf',
'extension' => 'pdf', 'extension' => 'pdf',
'size' => 512, 'size' => 512,
]); ]);
$tenant->attachments()->attach($attachment->getKey());
app(AttachmentService::class)->delete($attachment); app(AttachmentService::class)->delete($attachment);
@@ -117,6 +119,9 @@ class AttachmentTest extends TestCase
$this->assertDatabaseMissing('attachments', [ $this->assertDatabaseMissing('attachments', [
'id' => $attachment->id, '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 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', 'dominio' => 'umbrella.com',
]); ]);
$attachment = $tenant->attachments()->create([ $attachment = Attachment::query()->create([
'path' => 'attachments/umbrella/audio.mp3', 'path' => 'attachments/umbrella/audio.mp3',
'key' => (string) Str::uuid(),
'filename' => 'audio.mp3', 'filename' => 'audio.mp3',
'type' => AttachmentType::Audio, 'type' => AttachmentType::Audio,
'mime_type' => 'audio/mpeg', 'mime_type' => 'audio/mpeg',
'extension' => 'mp3', 'extension' => 'mp3',
'size' => 1024, 'size' => 1024,
]); ]);
$tenant->attachments()->attach($attachment->getKey());
$disk = Mockery::mock(); $disk = Mockery::mock();
Storage::shouldReceive('disk') Storage::shouldReceive('disk')
@@ -154,6 +161,11 @@ class AttachmentTest extends TestCase
$this->assertDatabaseHas('attachments', [ $this->assertDatabaseHas('attachments', [
'id' => $attachment->id, 'id' => $attachment->id,
]); ]);
$this->assertDatabaseHas('attachable_attachments', [
'attachment_id' => $attachment->id,
'attachable_type' => $tenant->getMorphClass(),
'attachable_id' => $tenant->getKey(),
]);
} }
} }
} }