Skip to content

Commit

Permalink
Handle Models that no longer exist
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanzweifel committed Mar 26, 2024
1 parent 2326c06 commit 66cacd4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Listeners/StoreOutgoingMailListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

Expand Down
31 changes: 31 additions & 0 deletions tests/Listeners/StoreOutgoingMailListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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('[email protected]')
->send($mailable);

assertDatabaseHas('sends', [
'mail_class' => null,
'subject' => '::subject::',
'to' => json_encode(['[email protected]' => 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();

Expand Down

0 comments on commit 66cacd4

Please sign in to comment.