Files
emails/api/common/Service/Remote/Messages.php
2022-11-29 08:57:56 -03:00

67 lines
2.1 KiB
PHP

<?php
namespace ProVM\Common\Service\Remote;
use DateTimeInterface;
use Ddeboer\Imap\Exception\MessageDoesNotExistException;
use Psr\Log\LoggerInterface;
use Ddeboer\Imap\ConnectionInterface;
use Ddeboer\Imap\MailboxInterface;
use Ddeboer\Imap\MessageInterface;
use Ddeboer\Imap\SearchExpression;
use Ddeboer\Imap\Search\Date\On;
use Ddeboer\Imap\Search\Email\From;
use Ddeboer\Imap\Search\Text\Subject;
use ProVM\Common\Exception\EmptyMailbox;
class Messages extends Base
{
public function __construct(ConnectionInterface $connection, LoggerInterface $logger)
{
$this->setConnection($connection)
->setLogger($logger);
}
public function getAll(MailboxInterface $mailbox, int $start = 0, ?int $amount = null): array
{
if ($mailbox->count() === 0) {
throw new EmptyMailbox($mailbox);
}
if ($amount === null) {
$amount = $mailbox->count() - $start;
}
$it = $mailbox->getIterator();
for ($i = 0; $i < $start; $i ++) {
$it->next();
}
$messages = [];
for ($i = $start; $i < $start + $amount; $i ++) {
if (!$it->valid()) {
break;
}
$messages[$i] = $it->current();
$it->next();
}
return $messages;
}
public function get(MailboxInterface $mailbox, string $subject, string $from, DateTimeInterface $dateTime): MessageInterface
{
if ($mailbox->count() === 0) {
$this->getLogger()->notice("Mailbox {$mailbox->getName()} is empty");
throw new EmptyMailbox($mailbox);
}
$query = new SearchExpression();
$query->addCondition(new Subject($subject));
$query->addCondition(new From($from));
$query->addCondition(new On($dateTime));
$result = $mailbox->getMessages($query);
if (count($result) === 0) {
throw new MessageDoesNotExistException("{$mailbox->getName()}: {$subject} - {$from} [{$dateTime->format('Y-m-d H:i:s')}]");
}
return $result->current();
}
}