Merge pull request #17736 from civicrm/5.27
[civicrm-core.git] / ext / flexmailer / src / Listener / DefaultBatcher.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11 namespace Civi\FlexMailer\Listener;
12
13 use Civi\FlexMailer\Event\WalkBatchesEvent;
14 use Civi\FlexMailer\FlexMailerTask;
15
16 class DefaultBatcher extends BaseListener {
17
18 /**
19 * Given a MailingJob (`$e->getJob()`), enumerate the recipients as
20 * a batch of FlexMailerTasks and visit each batch (`$e->visit($tasks)`).
21 *
22 * @param \Civi\FlexMailer\Event\WalkBatchesEvent $e
23 */
24 public function onWalk(WalkBatchesEvent $e) {
25 if (!$this->isActive()) {
26 return;
27 }
28
29 $e->stopPropagation();
30
31 $job = $e->getJob();
32
33 // CRM-12376
34 // This handles the edge case scenario where all the mails
35 // have been delivered in prior jobs.
36 $isDelivered = TRUE;
37
38 // make sure that there's no more than $mailerBatchLimit mails processed in a run
39 $mailerBatchLimit = \CRM_Core_Config::singleton()->mailerBatchLimit;
40
41 $eq = \CRM_Mailing_BAO_MailingJob::findPendingTasks($job->id, 'email');
42 $tasks = array();
43 while ($eq->fetch()) {
44 if ($mailerBatchLimit > 0 && \CRM_Mailing_BAO_MailingJob::$mailsProcessed >= $mailerBatchLimit) {
45 if (!empty($tasks)) {
46 $e->visit($tasks);
47 }
48 $eq->free();
49 $e->setCompleted(FALSE);
50 return;
51 }
52 \CRM_Mailing_BAO_MailingJob::$mailsProcessed++;
53
54 // FIXME: To support SMS, the address should be $eq->phone instead of $eq->email
55 $tasks[] = new FlexMailerTask($eq->id, $eq->contact_id, $eq->hash,
56 $eq->email);
57 if (count($tasks) == \CRM_Mailing_BAO_MailingJob::MAX_CONTACTS_TO_PROCESS) {
58 $isDelivered = $e->visit($tasks);
59 if (!$isDelivered) {
60 $eq->free();
61 $e->setCompleted($isDelivered);
62 return;
63 }
64 $tasks = array();
65 }
66 }
67
68 $eq->free();
69
70 if (!empty($tasks)) {
71 $isDelivered = $e->visit($tasks);
72 }
73 $e->setCompleted($isDelivered);
74 }
75
76 }