From 6a615b680fe386eee72928c4fc32ebea2ff93535 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Sat, 5 Apr 2025 13:36:26 -0400 Subject: [PATCH 1/2] Add firstOrFail method --- src/MessageQuery.php | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/MessageQuery.php b/src/MessageQuery.php index 14a90bb..f1cdd81 100644 --- a/src/MessageQuery.php +++ b/src/MessageQuery.php @@ -14,6 +14,7 @@ use DirectoryTree\ImapEngine\Support\ForwardsCalls; use DirectoryTree\ImapEngine\Support\Str; use Illuminate\Support\Collection; +use Illuminate\Support\ItemNotFoundException; use Illuminate\Support\Traits\Conditionable; /** @@ -430,7 +431,19 @@ protected function populate(Collection $uids): MessageCollection */ public function first(): ?MessageInterface { - return $this->limit(1)->get()->first(); + try { + return $this->firstOrFail(); + } catch (ItemNotFoundException) { + return null; + } + } + + /** + * Get the first message in the resulting collection or throw an exception. + */ + public function firstOrFail(): MessageInterface + { + return $this->limit(1)->get()->firstOrFail(); } /** From 3c66cd3c979a7dc0ca5bffdd3b83d5af76dc79c3 Mon Sep 17 00:00:00 2001 From: Steve Bauman Date: Sat, 5 Apr 2025 13:36:34 -0400 Subject: [PATCH 2/2] Add test --- tests/Integration/MessagesTest.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/Integration/MessagesTest.php b/tests/Integration/MessagesTest.php index 160630d..8f4a419 100644 --- a/tests/Integration/MessagesTest.php +++ b/tests/Integration/MessagesTest.php @@ -55,6 +55,18 @@ function folder(): Folder expect($folder->messages()->first()->uid())->toBe($uid); }); +test('first or fail', function () { + $folder = folder(); + + expect(fn () => $folder->messages()->firstOrFail())->toThrow(ItemNotFoundException::class); + + $uid = $folder->messages()->append( + new DraftMessage(from: 'foo@example.com', text: 'hello world'), + ); + + expect($folder->messages()->firstOrFail()->uid())->toBe($uid); +}); + test('find', function () { $folder = folder();