07-cron_emails_sender.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace cx_newsletter;
  3. class cron_emails_sender
  4. extends service
  5. implements service_interface {
  6. public function prepare() : self {
  7. $this->campaigns_repository = new campaigns_repository(
  8. $this->get_database(),
  9. $this->get_tables()
  10. );
  11. $this->send_log_repository = new send_log_repository(
  12. $this->get_database(),
  13. $this->get_tables()
  14. );
  15. $this->customers_mapper = new customers_mapper(
  16. $this->get_database(),
  17. $this->get_tables()
  18. );
  19. $this->messages_mapper = new messages_mapper(
  20. $this->get_database(),
  21. $this->get_tables()
  22. );
  23. return $this;
  24. }
  25. public function process() : self {
  26. $next_campaign = $this->campaigns_repository->load_next(
  27. campaign_type::email
  28. );
  29. if ($next_campaign === null) {
  30. return $this;
  31. }
  32. $customers = $this->send_log_repository->load_all(
  33. $next_campaign,
  34. $this->get_settings()->get('email_count'),
  35. false
  36. );
  37. if (empty($customers)) {
  38. $next_campaign->finalize();
  39. $this->campaigns_repository->save($next_campaign);
  40. return $this->process();
  41. }
  42. foreach ($customers as $customer) {
  43. if ($this->send($customer, $next_campaign->message)) {
  44. $this->send_log_repository->mark_send($next_campaign, $customer);
  45. }
  46. }
  47. return $this;
  48. }
  49. private function send(customer $to, message $what) : bool {
  50. if (empty($to->email)) {
  51. return false;
  52. }
  53. if (!$what->is_complete()) {
  54. return false;
  55. }
  56. $mail = new single_mail();
  57. $mail->title = $what->title;
  58. $mail->content = $what->content;
  59. $mail->to = $to->email;
  60. $mail->is_html = true;
  61. $mailer = new mail_manager($this->get_settings());
  62. $mailer->prepare($mail);
  63. return $mailer->send();
  64. }
  65. private campaigns_repository $campaigns_repository;
  66. private send_log_repository $send_log_repository;
  67. private customers_mapper $customers_mapper;
  68. private messages_mapper $messages_mapper;
  69. private campaign $what;
  70. }