|
3 | 3 | namespace DirectoryTree\ImapEngine; |
4 | 4 |
|
5 | 5 | use DirectoryTree\ImapEngine\Collections\MessageCollection; |
| 6 | +use DirectoryTree\ImapEngine\Collections\ResponseCollection; |
6 | 7 | use DirectoryTree\ImapEngine\Connection\ConnectionInterface; |
7 | 8 | use DirectoryTree\ImapEngine\Connection\ImapQueryBuilder; |
8 | 9 | use DirectoryTree\ImapEngine\Connection\Responses\UntaggedResponse; |
@@ -525,24 +526,44 @@ public function paginate(int $perPage = 5, $page = null, string $pageName = 'pag |
525 | 526 | return $this->get()->paginate($perPage, $this->page, $pageName, true); |
526 | 527 | } |
527 | 528 |
|
| 529 | + /** |
| 530 | + * Find a message by the given identifier type or throw an exception. |
| 531 | + */ |
| 532 | + public function findOrFail(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid) |
| 533 | + { |
| 534 | + $uid = $this->uid($id, $identifier) |
| 535 | + ->firstOrFail() // Untagged response |
| 536 | + ->tokenAt(3) // ListData |
| 537 | + ->tokenAt(1) // Atom |
| 538 | + ->value; // UID |
| 539 | + |
| 540 | + return $this->process(new MessageCollection([$uid]))->firstOrFail(); |
| 541 | + } |
| 542 | + |
528 | 543 | /** |
529 | 544 | * Find a message by the given identifier type. |
530 | 545 | */ |
531 | | - public function find(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): Message |
| 546 | + public function find(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ?Message |
532 | 547 | { |
533 | | - // If the sequence is not UID, we'll need to fetch the UID first. |
534 | | - $uid = match ($identifier) { |
535 | | - ImapFetchIdentifier::Uid => $id, |
536 | | - ImapFetchIdentifier::MessageNumber => $this->connection()->uid([$id]) // ResponseCollection |
537 | | - ->firstOrFail() // Untagged response |
538 | | - ->tokenAt(3) // ListData |
539 | | - ->tokenAt(1) // Atom |
540 | | - ->value // UID |
541 | | - }; |
| 548 | + if (! $response = $this->uid($id, $identifier)->first()) { |
| 549 | + return null; |
| 550 | + } |
| 551 | + |
| 552 | + $uid = $response->tokenAt(3) // ListData |
| 553 | + ->tokenAt(1) // Atom |
| 554 | + ->value; // UID |
542 | 555 |
|
543 | 556 | return $this->process(new MessageCollection([$uid]))->first(); |
544 | 557 | } |
545 | 558 |
|
| 559 | + /** |
| 560 | + * Get the UID for theb given identifier. |
| 561 | + */ |
| 562 | + protected function uid(int $id, ImapFetchIdentifier $identifier = ImapFetchIdentifier::Uid): ResponseCollection |
| 563 | + { |
| 564 | + return $this->connection()->uid([$id], $identifier); |
| 565 | + } |
| 566 | + |
546 | 567 | /** |
547 | 568 | * Get the connection instance. |
548 | 569 | */ |
|
0 commit comments