From 66cacd47d3787794aeb3cc2264982e5730d3e680 Mon Sep 17 00:00:00 2001 From: Stefan Zweifel Date: Tue, 26 Mar 2024 19:45:52 +0100 Subject: [PATCH] Handle Models that no longer exist --- src/Listeners/StoreOutgoingMailListener.php | 5 +-- .../StoreOutgoingMailListenerTest.php | 31 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/Listeners/StoreOutgoingMailListener.php b/src/Listeners/StoreOutgoingMailListener.php index d05ff5e..ee48d96 100644 --- a/src/Listeners/StoreOutgoingMailListener.php +++ b/src/Listeners/StoreOutgoingMailListener.php @@ -132,14 +132,15 @@ protected function getModels(MessageSent $event): Collection $modelsArray = json_decode($models, true, 512, JSON_THROW_ON_ERROR); return collect($modelsArray) - ->map(function (array $tuple): Model { + ->map(function (array $tuple): ?Model { /** @var Model $model */ $model = $tuple['model']; $id = $tuple['id']; - /** @phpstan-ignore-next-line */ + /** @phpstan-var ?Model */ return $model::find($id); }) + ->filter() ->filter(fn (Model $model) => (new ReflectionClass($model))->implementsInterface(HasSends::class)); } diff --git a/tests/Listeners/StoreOutgoingMailListenerTest.php b/tests/Listeners/StoreOutgoingMailListenerTest.php index c6f15cf..50a148e 100644 --- a/tests/Listeners/StoreOutgoingMailListenerTest.php +++ b/tests/Listeners/StoreOutgoingMailListenerTest.php @@ -181,6 +181,37 @@ ]); }); +it('attaches related models to a send model by passing arguments to associateWith method but discard models that no longer exist', function () { + $testModel = TestModel::create(); + $anotherTestModel = AnotherTestModel::create(); + + $mailable = new TestMailWithRelatedModelsHeaderPassAsArguments($testModel, $anotherTestModel); + + $testModel->delete(); + + Mail::to('test@example.com') + ->send($mailable); + + assertDatabaseHas('sends', [ + 'mail_class' => null, + 'subject' => '::subject::', + 'to' => json_encode(['test@example.com' => null]), + 'cc' => null, + 'bcc' => null, + ['sent_at', '!=', null], + ]); + assertDatabaseMissing('sendables', [ + 'send_id' => 1, + 'sendable_type' => TestModel::class, + 'sendable_id' => 1, + ]); + assertDatabaseHas('sendables', [ + 'send_id' => 1, + 'sendable_type' => AnotherTestModel::class, + 'sendable_id' => 2, + ]); +}); + it('attaches related models to a send model based on the public properties of the mail class', function () { $testModel = TestModel::create();