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\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<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 Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
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\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;
}
}

View File

@@ -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
{
return response()->json(
$this->s3TestService->storeTestFile(
$attachment = $this->attachmentService->store(
$request->file('file'),
$request->validated('directory'),
$request->validated('path'),
);
$temporaryUrl = $this->s3TestService->generateTemporaryUrl(
$attachment->path,
(int) $request->validated('expires_in_minutes', 10),
),
);
return response()->json(
[
'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,
);
}

View File

@@ -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'],
];
}

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');
$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(),
]);
}
}
}