SpoolList.php in Simplenews 3.x
File
src/Spool/SpoolList.php
View source
<?php
namespace Drupal\simplenews\Spool;
use Drupal\simplenews\AbortSendingException;
use Drupal\simplenews\Entity\Subscriber;
use Drupal\simplenews\Mail\MailEntity;
class SpoolList implements SpoolListInterface {
const MAX_ERRORS = 50;
protected $spoolStorage;
protected $spoolRows;
protected $pendingErrors = [];
protected $consecutivePendingErrors = 0;
protected $success = FALSE;
public function __construct(array $spool_rows, SpoolStorageInterface $spool_storage) {
$this->spoolRows = $spool_rows;
$this->spoolStorage = $spool_storage;
}
public function count() {
return count($this->spoolRows);
}
public function nextMail() {
$spool_data = current($this->spoolRows);
if (!$spool_data) {
return FALSE;
}
$issue = \Drupal::entityTypeManager()
->getStorage($spool_data->entity_type)
->load($spool_data->entity_id);
if (!$issue) {
$this
->setLastMailResult(SpoolStorageInterface::STATUS_SKIPPED);
return $this
->nextMail();
}
if (!empty($spool_data->data)) {
$subscriber = Subscriber::create(unserialize($spool_data->data));
}
else {
$subscriber = Subscriber::load($spool_data->snid);
}
if (!$subscriber || !$subscriber
->getMail()) {
$this
->setLastMailResult(SpoolStorageInterface::STATUS_SKIPPED);
return $this
->nextMail();
}
$mail = new MailEntity($issue, $subscriber, \Drupal::service('simplenews.mail_cache'));
$spool_data->langcode = $mail
->getLanguage();
return $mail;
}
public function setLastMailResult($result) {
$spool_data = current($this->spoolRows);
$spool_data->result = $result;
if ($result == SpoolStorageInterface::STATUS_PENDING) {
$this->pendingErrors[] = $spool_data->msid;
$this->consecutivePendingErrors++;
if ($this->consecutivePendingErrors > static::MAX_ERRORS) {
throw new AbortSendingException('Maximum error limit exceeded');
}
}
$this->spoolStorage
->updateMails([
$spool_data->msid,
], $result);
if ($result == SpoolStorageInterface::STATUS_DONE) {
$this->consecutivePendingErrors = 0;
$this->success = TRUE;
}
next($this->spoolRows);
}
public function getResults() {
if ($this->success && $this->pendingErrors) {
$this->spoolStorage
->updateMails($this->pendingErrors, SpoolStorageInterface::STATUS_FAILED);
foreach ($this->pendingErrors as $msid) {
$this->spoolRows[$msid]->result = SpoolStorageInterface::STATUS_FAILED;
}
}
if ($msid = key($this->spoolRows)) {
$spool_ids = array_keys($this->spoolRows);
$offset = array_search($msid, $spool_ids);
$this->spoolStorage
->updateMails(array_slice($spool_ids, $offset), SpoolStorageInterface::STATUS_PENDING);
$this->spoolRows = array_slice($this->spoolRows, 0, $offset);
}
return $this->spoolRows;
}
}