From e9bbadd6c0b6c0a92dcb55d33e0a7dc9b515b554 Mon Sep 17 00:00:00 2001 From: Micah Shackelford Date: Sun, 21 Jan 2024 13:55:51 -0600 Subject: [PATCH] fix: delete image if shot deleted --- app/Models/Shot.php | 17 +++++++++++++++++ .../Http/Controllers/ShotControllerTest.php | 14 ++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/app/Models/Shot.php b/app/Models/Shot.php index 921a9d3..63f130d 100644 --- a/app/Models/Shot.php +++ b/app/Models/Shot.php @@ -2,13 +2,17 @@ namespace App\Models; +use Exception; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; +use Throwable; /** * @property int $id @@ -47,6 +51,19 @@ protected static function booted(): void 'uuid' => (string) Str::orderedUuid(), ]); }); + + static::deleting(function (Shot $shot) { + try { + if (! Storage::delete($shot->path)) { + throw new Exception('Missing file'); + } + } catch (Throwable $th) { + Log::warning('Unable to delete shot', [ + 'path' => $shot->path, + 'exception' => $th, + ]); + } + }); } protected function links(): Attribute diff --git a/tests/Unit/Http/Controllers/ShotControllerTest.php b/tests/Unit/Http/Controllers/ShotControllerTest.php index 99ffc93..0190d5c 100644 --- a/tests/Unit/Http/Controllers/ShotControllerTest.php +++ b/tests/Unit/Http/Controllers/ShotControllerTest.php @@ -6,6 +6,7 @@ use App\Models\Shot; use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Storage; use Inertia\Testing\AssertableInertia as Assert; use Tests\TestCase; @@ -123,13 +124,18 @@ public function test_update_updates_shots_name() public function test_destroy_deletes_shot() { - [$shot, $_] = $this->createShot(true); + Storage::fake(); + + [$shot, $_] = $this->createShot(true, shotData: [ + 'path' => Storage::put($path = 'img.png', 'contents'), + ]); $this->actingAs($this->user) ->delete(route('shots.destroy', $shot->id)) ->assertNoContent(); - $this->assertNull($shot->fresh(), 'it deletes shot'); + $this->assertNull($shot->fresh(), 'it deletes shot record'); + $this->assertFileDoesNotExist($path, 'it deletes image file'); } public function test_users_can_react_to_a_shot() @@ -165,9 +171,9 @@ public function test_users_can_react_to_a_shot() $this->assertCount(0, $reactions = $shot->reactions()->get(), 'it toggles existing reaction'); } - protected function createShot(bool $onlyShot = false): array + protected function createShot(bool $onlyShot = false, array $shotData = []): array { - $shot = $this->user->shots()->save(Shot::factory()->make()); + $shot = $this->user->shots()->save(Shot::factory()->make($shotData)); if (! $onlyShot) { // Create "childShots"