diff --git a/src/Fetch/Server.php b/src/Fetch/Server.php index 17f572a..4fca523 100644 --- a/src/Fetch/Server.php +++ b/src/Fetch/Server.php @@ -374,6 +374,23 @@ class Server return $messages; } + /** + * Returns the emails in the current mailbox as an array of ImapMessage objects + * ordered by some ordering + * + * @see http://php.net/manual/en/function.imap-sort.php + * @param int $orderBy + * @param bool $reverse + * @param int $limit + * @return Message[] + */ + public function getOrdered($orderBy, $reverse, $limit) + { + $msgIds = imap_sort($this->getImapStream(), $orderBy, $reverse ? 1 : 0, SE_UID); + + return array_map(array($this, 'getMessageByUid'), array_slice($msgIds, 0, $limit)); + } + /** * Returns the requested email or false if it is not found. * diff --git a/tests/Fetch/Test/ServerTest.php b/tests/Fetch/Test/ServerTest.php index 0d854ad..4255ed2 100644 --- a/tests/Fetch/Test/ServerTest.php +++ b/tests/Fetch/Test/ServerTest.php @@ -113,6 +113,24 @@ class ServerTest extends \PHPUnit_Framework_TestCase } } + public function testGetMessagesOrderedByDateAsc() + { + $server = Static::getServer(); + $messages = $server->getOrdered(SORTDATE, false, 2); + + $this->assertCount(2, $messages, 'Two messages returned'); + $this->assertGreaterThan($messages[0]->getDate(), $messages[1]->getDate(), 'Messages in ascending order'); + } + + public function testGetMessagesOrderedByDateDesc() + { + $server = Static::getServer(); + $messages = $server->getOrdered(SORTDATE, true, 2); + + $this->assertCount(2, $messages, 'Two messages returned'); + $this->assertLessThan($messages[0]->getDate(), $messages[1]->getDate(), 'Messages in descending order'); + } + public function testGetMailBox() { $server = Static::getServer();