diff --git a/src/MessageQuery.php b/src/MessageQuery.php index e790d25..204a769 100644 --- a/src/MessageQuery.php +++ b/src/MessageQuery.php @@ -261,21 +261,37 @@ protected function fetch(Collection $messages): array 'desc' => $messages->sortDesc(SORT_NUMERIC), }; - $uids = $messages->forPage($this->page, $this->limit) - ->values() - ->all(); + $uids = $messages->forPage($this->page, $this->limit)->values(); - $response = $this->connection()->fetch(array_filter([ - $this->fetchFlags ? 'FLAGS' : null, - $this->fetchBody ? $this->fetchAsUnread + $fetch = []; + + if ($this->fetchFlags) { + $fetch[] = 'FLAGS'; + } + + if ($this->fetchBody) { + $fetch[] = $this->fetchAsUnread ? 'BODY.PEEK[TEXT]' - : 'BODY[TEXT]' : null, - $this->fetchHeaders ? $this->fetchAsUnread + : 'BODY[TEXT]'; + } + + if ($this->fetchHeaders) { + $fetch[] = $this->fetchAsUnread ? 'BODY.PEEK[HEADER]' - : 'BODY[HEADER]' : null, - ]), $uids); + : 'BODY[HEADER]'; + } + + if (empty($fetch)) { + return $uids->mapWithKeys(fn (string|int $uid) => [ + $uid => [ + 'flags' => [], + 'headers' => '', + 'contents' => '', + ], + ])->all(); + } - return $response->mapWithKeys(function (UntaggedResponse $response) { + return $this->connection()->fetch($fetch, $uids->all())->mapWithKeys(function (UntaggedResponse $response) { $data = $response->tokenAt(3); $uid = $data->lookup('UID')->value; diff --git a/tests/Integration/MessagesTest.php b/tests/Integration/MessagesTest.php index d641fdc..4e66426 100644 --- a/tests/Integration/MessagesTest.php +++ b/tests/Integration/MessagesTest.php @@ -5,6 +5,7 @@ use DirectoryTree\ImapEngine\DraftMessage; use DirectoryTree\ImapEngine\Folder; use DirectoryTree\ImapEngine\Message; +use DirectoryTree\ImapEngine\MessageQuery; use Illuminate\Support\ItemNotFoundException; function folder(): Folder @@ -99,6 +100,42 @@ function folder(): Folder })->toThrow(ItemNotFoundException::class); }); +test('get without fetches', function () { + $folder = folder(); + + $uid = $folder->messages()->append( + new DraftMessage( + from: 'foo@email.com', + text: 'hello world', + ), + ); + + $messages = $folder->messages()->get(); + + expect($messages->count())->toBe(1); + expect($messages->first()->uid())->toBe($uid); +}); + +test('get with fetches', function (callable $callback) { + $folder = folder(); + + $uid = $folder->messages()->append( + new DraftMessage( + from: 'foo@email.com', + text: 'hello world', + ), + ); + + $messages = $callback($folder->messages())->get(); + + expect($messages->count())->toBe(1); + expect($messages->first()->uid())->toBe($uid); +})->with([ + fn (MessageQuery $query) => $query->withBody(), + fn (MessageQuery $query) => $query->withFlags(), + fn (MessageQuery $query) => $query->withHeaders(), +]); + test('append', function () { $folder = folder();