This commit is contained in:
Lizandro Guarnizo
2026-04-25 14:55:11 -05:00
parent 2228818c85
commit fa1f4bc581
2 changed files with 44 additions and 9 deletions
+37 -8
View File
@@ -29,10 +29,16 @@ class CorreoImapService
// ──────────────────────────────────────────────
/**
* Conecta, autentica y devuelve los últimos $limit correos.
* Cada elemento: [uid, from, subject, date, body]
* Conecta, autentica y devuelve:
* - Los correos de los últimos $minutesBack minutos, con máximo $limit emails.
* - Lo que ocurra primero: llegar al límite de tiempo o al límite de cantidad.
*
* Para tener margen suficiente se descarga un lote mayor ($fetchSize) y
* luego se filtra por fecha en PHP.
*
* Cada elemento: [seq, from, subject, date, body]
*/
public function fetchLatest(int $limit = 5): array
public function fetchLatest(int $limit = 5, int $minutesBack = 5): array
{
$this->connect();
$this->login();
@@ -43,16 +49,39 @@ class CorreoImapService
return [];
}
// Tomamos los últimos $limit números de secuencia
$from = max(1, $total - $limit + 1);
// Descargar un lote suficiente para cubrir la ventana de tiempo.
// 20 mensajes es razonable; si el buzón tiene pocos, se ajusta.
$fetchSize = min($total, max($limit * 4, 20));
$from = max(1, $total - $fetchSize + 1);
$set = "{$from}:{$total}";
$emails = $this->fetchMessages($set);
$this->logout();
// Devolver en orden descendente (más reciente primero)
return array_reverse($emails);
// Más reciente primero
$emails = array_reverse($emails);
$cutoff = time() - ($minutesBack * 60);
$result = [];
foreach ($emails as $email) {
// Parsear la fecha del correo
$ts = $email['date'] ? @strtotime($email['date']) : false;
// Si la fecha es válida y el correo es más antiguo que la ventana → parar
if ($ts !== false && $ts < $cutoff) {
break;
}
$result[] = $email;
// Límite de cantidad alcanzado → parar
if (count($result) >= $limit) {
break;
}
}
return $result;
}
public function getLastError(): string