Skip to content

Commit

Permalink
refactor!: throw exception if model cannot be soft deleted #371 (#34)
Browse files Browse the repository at this point in the history
Covers the scenario where a listener or observer prevents a model from being
soft-deleted. When this happens, an exception is thrown as we cannot honour
the client's request and are in an invalid state.
  • Loading branch information
foxbecoding authored Mar 12, 2024
1 parent 01aa76a commit d9d6221
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Drivers/SoftDeleteDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use InvalidArgumentException;
use RuntimeException;

class SoftDeleteDriver extends StandardDriver
{
Expand Down Expand Up @@ -81,11 +82,23 @@ public function persist(Model $model): bool
* @see https://github.com/cloudcreativity/laravel-json-api/issues/371
*/
if ($this->willSoftDelete($model)) {
assert(method_exists($model, 'getDeletedAtColumn'));
$column = $model->getDeletedAtColumn();
// save the original date so we can put it back later on.
$deletedAt = $model->{$column};
// delete the record so that deleting and deleted events get fired.
$model->delete();
$response = $model->delete(); // capture the response

// if a listener prevented the delete from happening, we need to throw as we are in an invalid state.
// developers should prevent this scenario from happening either through authorization or validation.
if ($response === false) {
throw new RuntimeException(sprintf(
'Failed to soft delete model - %s:%s',
$model::class,
$model->getKey(),
));
}

// apply the original date back before saving, so that we keep date provided by the client.
$model->{$column} = $deletedAt;
}
Expand Down
17 changes: 17 additions & 0 deletions tests/lib/Acceptance/SoftDeleteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,23 @@ public function testItDoesNotSoftDeleteOnUpdate(): void
]));
}

public function testItDoesNotSoftDeleteOnUpdateIfListenerReturnsFalse(): void
{
$post = Post::factory()->create(['deleted_at' => null]);

$data = ['deletedAt' => now()->toJSON(), 'title' => 'Hello World!'];

Post::deleting(fn() => false);

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Failed to soft delete model - App\Models\Post:' . $post->getKey());

$this->schema
->repository()
->update($post)
->store($data);
}

public function testItRestores(): void
{
$restored = false;
Expand Down

0 comments on commit d9d6221

Please sign in to comment.