Skip to content

Commit

Permalink
Remove failed DB record even when using SoftDeletes (#3142)
Browse files Browse the repository at this point in the history
* Remove failed DB record when using SoftDeletes

* Add test case for media add failure w softdeletes
  • Loading branch information
Pilskalns authored Jan 5, 2023
1 parent 05b0264 commit 644ce1b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/MediaCollections/FileAdder.php
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ protected function processMediaItem(HasMedia $model, Media $media, self $fileAdd
}

if (! $addedMediaSuccessfully) {
$media->delete();
$media->forceDelete();

throw DiskCannotBeAccessed::create($media->disk);
}
Expand Down
35 changes: 34 additions & 1 deletion tests/Feature/FileAdder/IntegrationTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;
use Spatie\MediaLibrary\MediaCollections\Exceptions\DiskCannotBeAccessed;
use Spatie\MediaLibrary\MediaCollections\Exceptions\DiskDoesNotExist;
Expand All @@ -13,6 +14,7 @@
use Spatie\MediaLibrary\MediaCollections\Exceptions\UnreachableUrl;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Spatie\MediaLibrary\Tests\TestSupport\RenameOriginalFileNamer;
use Spatie\MediaLibrary\Tests\TestSupport\TestModels\TestModel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

it('can add an file to the default collection', function () {
Expand Down Expand Up @@ -597,7 +599,7 @@
expect($result->getStatusCode())->toEqual(200);
});

it('will throw and exception and not create a record in database if file cannot be added', function () {
it('will throw an exception and revert database when file cannot be added', function () {
$this->testModel
->addMedia($this->getTestPng())
->toMediaCollection();
Expand All @@ -620,3 +622,34 @@

expect(Media::count())->toBe(1);
});

it('will throw an exception and revert database when file cannot be added and model uses softdeletes', function () {
$testModelClass = new class () extends TestModel {
use SoftDeletes;
};

/** @var TestModel $testModel */
$testModel = $testModelClass::find($this->testModel->id);

$testModel
->addMedia($this->getTestPng())
->toMediaCollection();

expect(Media::count())->toBe(1);

config()->set('filesystems.disks.invalid_disk', [
'driver' => 's3',
'secret' => 'test',
'key' => 'test',
'region' => 'test',
'bucket' => 'test',
]);

expect(
fn () => $testModel
->addMedia($this->getTestJpg())
->toMediaCollection('default', 'invalid_disk')
)->toThrow(DiskCannotBeAccessed::class);

expect(Media::count())->toBe(1);
});

0 comments on commit 644ce1b

Please sign in to comment.