Skip to content
This repository was archived by the owner on Jul 2, 2024. It is now read-only.

fix store mail also on failing route #2

Merged
merged 2 commits into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 20 additions & 17 deletions src/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,22 +84,25 @@ protected function createRoute(string $subject, string $pattern, $action): Route
public function callMailboxes(InboundEmail $email)
{
if ($email->isValid()) {
$matchedRoutes = $this->routes->match($email)->map(function (Route $route) use ($email) {
$route->run($email);
});

if ($matchedRoutes->isEmpty() && $this->fallbackRoute) {
$matchedRoutes[] = $this->fallbackRoute;
$this->fallbackRoute->run($email);
}

if ($this->catchAllRoute) {
$matchedRoutes[] = $this->catchAllRoute;
$this->catchAllRoute->run($email);
}

if ($this->shouldStoreInboundEmails() && $this->shouldStoreAllInboundEmails($matchedRoutes)) {
$this->storeEmail($email);
$matchedRoutes = $this->routes->match($email);
try {
$matchedRoutes->map(function (Route $route) use ($email) {
$route->run($email);
});

if ($matchedRoutes->isEmpty() && $this->fallbackRoute) {
$matchedRoutes[] = $this->fallbackRoute;
$this->fallbackRoute->run($email);
}

if ($this->catchAllRoute) {
$matchedRoutes[] = $this->catchAllRoute;
$this->catchAllRoute->run($email);
}
} finally {
if ($this->shouldStoreInboundEmails() && $this->shouldStoreAllInboundEmails($matchedRoutes)) {
$this->storeEmail($email);
}
}
}
}
Expand All @@ -111,7 +114,7 @@ protected function shouldStoreInboundEmails(): bool

protected function shouldStoreAllInboundEmails(Collection $matchedRoutes): bool
{
return $matchedRoutes->isNotEmpty() ? true : ! config('mailbox.only_store_matching_emails');
return $matchedRoutes->isNotEmpty() || ! config('mailbox.only_store_matching_emails');
}

protected function storeEmail(InboundEmail $email)
Expand Down
17 changes: 17 additions & 0 deletions tests/InboundEmailTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,23 @@ public function it_stores_all_inbound_emails()
$this->assertSame(2, InboundEmail::query()->count());
}

/** @test */
public function it_stores_all_inbound_emails_on_exception()
{
$this->app['config']['mailbox.only_store_matching_emails'] = false;

Mailbox::to('[email protected]', function ($email) {
throw new \Exception("expect to fail");
});

try {
Mail::to('[email protected]')->send(new TestMail);
} catch(\Throwable $e){}
Mail::to('[email protected]')->send(new TestMail);

$this->assertSame(2, InboundEmail::query()->count());
}

/** @test */
public function it_can_use_fallbacks()
{
Expand Down