Skip to content

Commit

Permalink
fix: delete image if shot deleted
Browse files Browse the repository at this point in the history
  • Loading branch information
mdshack committed Jan 21, 2024
1 parent 4183f4d commit e9bbadd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
17 changes: 17 additions & 0 deletions app/Models/Shot.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
14 changes: 10 additions & 4 deletions tests/Unit/Http/Controllers/ShotControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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"
Expand Down

0 comments on commit e9bbadd

Please sign in to comment.